// ==UserScript==
// @name           KoCPaAB/T 
// @version        23.b1
// @namespace      MAD_HATTER
// @description    Kingdom of Camelot 
// @homepage       http://www.freewebs.com/kocbot/

// @include        *kingdomsofcamelot.com/*main_src.php*
// @include        *kingdomsofcamelot.com/*fbLoginButton.php*
// @include        *kingdomsofcamelot.com/*standAlone.php*
// @include        *kingdomsofcamelot.com/*platforms/kabam*
// @include        *kingdomsofcamelot.com/*acceptToken_src.php*
// @include        *kingdomsofcamelot.com/*helpFriend_src.php*
// @include        *kingdomsofcamelot.com/*newgameV2_src.php*
// @include        *apps.facebook.com/kingdomsofcamelot/*
// @include        *facebook.com/connect/uiserver.php*
// @include        *facebook.com/*/serverfbml*
// @include        *facebook.com/dialog/feed*
// @include        *facebook.com/dialog/stream.publish*
// @include        *facebook.com/dialog/apprequests*
// @include        *kabam.com/*

// @resource       en http://koc-power-pdx.googlecode.com/svn/beta/langpacks/en.js
// @resource       de http://koc-power-pdx.googlecode.com/svn/beta/langpacks/de.js
// @resource       es http://koc-power-pdx.googlecode.com/svn/beta/langpacks/es.js
// @resource       fr http://koc-power-pdx.googlecode.com/svn/beta/langpacks/fr.js
// @resource       gr http://koc-power-pdx.googlecode.com/svn/beta/langpacks/gr.js
// @resource       it http://koc-power-pdx.googlecode.com/svn/beta/langpacks/it.js
// @resource       pt http://koc-power-pdx.googlecode.com/svn/beta/langpacks/pt.js
// @resource       tr http://koc-power-pdx.googlecode.com/svn/beta/langpacks/tr.js
// @resource       SR http://koc-power-pdx.googlecode.com/svn/beta/langpacks/SR.js

// @resource       PLUGIN_IMAGES http://koc-power-pdx.googlecode.com/svn/beta/plugins/images.js
// @resource       PLUGIN_AVATAR http://koc-power-pdx.googlecode.com/svn/beta/plugins/avatars.js
// @resource       PLUGIN_SMILEYS http://mad-hatters-magic.googlecode.com/svn/release/3/plugins/smileys.js
// @resource       PLUGIN_BUTTLER http://koc-power-pdx.googlecode.com/svn/beta/plugins/buttler.js

// @resource       MULTI_TABS http://koc-power-pdx.googlecode.com/svn/beta/plugins/tabs.js


var ScriptName = 'KoC Power ALL';
var releaseVersion=true; // false = Beta || true = Release
var Version = '23.b1';
var LangpackVersion= '1';
var KsLangpackFolderId = '303';
var homePage="http://www.freewebs.com/kocbot/";
var MAP_DELAY = 1300;
var DETECT_LEVEL_FS = false;
//var JSON;if(!JSON){JSON={}}(function(){function str(a,b){var c,d,e,f,g=gap,h,i=b[a];if(i&&typeof i==="object"&&typeof i.toJSON==="function"){i=i.toJSON(a)}if(typeof rep==="function"){i=rep.call(b,a,i)}switch(typeof i){case"string":return quote(i);case"number":return isFinite(i)?String(i):"null";case"boolean":case"null":return String(i);case"object":if(!i){return"null"}gap+=indent;h=[];if(Object.prototype.toString.apply(i)==="[object Array]"){f=i.length;for(c=0;c<f;c+=1){h[c]=str(c,i)||"null"}e=h.length===0?"[]":gap?"[\n"+gap+h.join(",\n"+gap)+"\n"+g+"]":"["+h.join(",")+"]";gap=g;return e}if(rep&&typeof rep==="object"){f=rep.length;for(c=0;c<f;c+=1){if(typeof rep[c]==="string"){d=rep[c];e=str(d,i);if(e){h.push(quote(d)+(gap?": ":":")+e)}}}}else{for(d in i){if(Object.prototype.hasOwnProperty.call(i,d)){e=str(d,i);if(e){h.push(quote(d)+(gap?": ":":")+e)}}}}e=h.length===0?"{}":gap?"{\n"+gap+h.join(",\n"+gap)+"\n"+g+"}":"{"+h.join(",")+"}";gap=g;return e}}function quote(a){escapable.lastIndex=0;return escapable.test(a)?'"'+a.replace(escapable,function(a){var b=meta[a];return typeof b==="string"?b:"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})+'"':'"'+a+'"'}function f(a){return a<10?"0"+a:a}"use strict";if(typeof Date.prototype.toJSON!=="function"){Date.prototype.toJSON=function(a){return isFinite(this.valueOf())?this.getUTCFullYear()+"-"+f(this.getUTCMonth()+1)+"-"+f(this.getUTCDate())+"T"+f(this.getUTCHours())+":"+f(this.getUTCMinutes())+":"+f(this.getUTCSeconds())+"Z":null};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(a){return this.valueOf()}}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={"\b":"\\b","\t":"\\t","\n":"\\n","\f":"\\f","\r":"\\r",'"':'\\"',"\\":"\\\\"},rep;if(typeof JSON.stringify!=="function"){JSON.stringify=function(a,b,c){var d;gap="";indent="";if(typeof c==="number"){for(d=0;d<c;d+=1){indent+=" "}}else if(typeof c==="string"){indent=c}rep=b;if(b&&typeof b!=="function"&&(typeof b!=="object"||typeof b.length!=="number")){throw new Error("JSON.stringify")}return str("",{"":a})}}if(typeof JSON.parse!=="function"){JSON.parse=function(text,reviver){function walk(a,b){var c,d,e=a[b];if(e&&typeof e==="object"){for(c in e){if(Object.prototype.hasOwnProperty.call(e,c)){d=walk(e,c);if(d!==undefined){e[c]=d}else{delete e[c]}}}}return reviver.call(a,b,e)}var j;text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return"\\u"+("0000"+a.charCodeAt(0).toString(16)).slice(-4)})}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,"@").replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,"]").replace(/(?:^|:|,)(?:\s*\[)+/g,""))){j=eval("("+text+")");return typeof reviver==="function"?walk({"":j},""):j}throw new SyntaxError("JSON.parse")}}})()
var JSON2 = JSON;

//Kabams new cheat detector
unsafeWindow.arthurCheck = function (a) {
  var b = false;
  for (var c = 0; c < a.length; c++) {
    if ($(unescape(a[c]))) {
      b = true;
      break
    }
  }
  if (b) {
    unsafeWindow.AjaxCall.gPostRequest("ajax/funnelTracking.php", {
      action: 1300,
      serverId: unsafeWindow.g_server,
      uid: unsafeWindow.moderators[Math.floor((Math.random()*unsafeWindow.moderators.length))]
    })
  }
};

/** <HOTFIX DetectLoadError> **/
if(/.*kingdomsofcamelot\.com\/.*main_src\.php.*/.test(window.location.href)) DetectLoadError();
function DetectLoadError(){
    var elmt=document.getElementById("errorPageContainer");
    if(elmt!=null) {
        logit("DetectLoadError: WARNING Auto reload because error page detected.");
        history.go(0);
        return;
    }
    elmt=document.getElementById("topnavDisplayName");
    if(elmt!=null) {
        logit("DetectLoadError: KoC loaded")
        return;
    }
    setTimeout(function(){DetectLoadError();},5000);
}
/** </HOTFIX DetectLoadError> **/

eval(GM_getResourceText( 'PLUGIN_IMAGES' ));

var langpacks = {"en" : true, "de" : true, "fr" : true, "it" : true, "tr" : true, "es" : true, "gr" : true, "pt" : true};
var LangOptions = {    culang : 'en',    langpacks : {"en" : true, "de" : true, "fr" : true, "it" : true, "tr" : true, "es" : true, "gr" : true, "pt" : true},};
readLangOptions();
LangOptions.langpacks = langpacks;
if (LangOptions.culang.length != 2) LangOptions.culang = "en";
var culang;
if (!langpack) { var langpack = new Object() };
langpack.loaded = false;
eval(GM_getResourceText( LangOptions.culang ));
culang = langpack;
culang.doTranslate=function(text){
    // Replaces alle placeholders in text with corresponding values from culang
    // {%key%}  == culang.key

    var pattern=/{%([a-z0-9_$]+)%}/gi;
    var keys=Array();
    while (result = pattern.exec(text)) {
        var key=result[1];
        //GM_log(key);
        var found=false; for(var i=0;i<keys.length;i++){if(keys[i]==key){found=true;break;}}
        if(found) continue;
        keys.push(key);
    }
    var s=text;
    for(var i=0;i<keys.length;i++){
        var key=keys[i];
        if(typeof(culang[key])=="undefined") {
            logit("WARNING: Missing translation! 'culang."+key+"' Language: '"+LangOptions.culang+"'");
            continue;
        }
        var exp=new RegExp("{%"+key+"%}","g");
        s=s.replace(exp,culang[key])
    } return s; 
}
/****************************************************************************
 *         multi language string resources (kocpdx.SR.js)                         *
 ****************************************************************************/
if(document.body.id == 'mainbody'){
    var SR={languages:["en","de","fr","it","tr","es","se","nl"]};
    for(var iSL=0;iSL<SR.languages.length;iSL++){SR[SR.languages[iSL]]={};}
    SR.getArray=function (entryKey, defLang){
        var tkArray=new Array();
        var tkLangArray2=[defLang].concat(SR.languages);
        for(var tkL=0;tkL<tkLangArray2.length;tkL++){
            var tkLang=tkLangArray2[tkL];
            if(typeof(SR[tkLang])==="undefined") continue;
            for(var tkX=1;;tkX++){
                if(typeof(SR[tkLang][entryKey+"_"+tkX])==="undefined") break;
                tkEntry=SR[tkLang][entryKey+"_"+tkX];
                tkExist=false;
                for(var tkAi=0;tkAi<tkArray.length;tkAi++){
                    if(tkArray[tkAi]===tkEntry){tkExist=true;break;}
                }
                if(tkExist) continue;
                tkArray.push(tkEntry);
            }
        } return tkArray;
    };
    try{eval(GM_getResourceText('SR'));SR.loaded=true;}
    catch(ex){
        GM_log("ERROR: loading kocpdx.SR.js"+"\n"+ex);
        srErrDiv=document.createElement("div");
        srErrDiv.innerHTML="ERROR loading kocpdx.SR.js!";
        srErrDiv.setAttribute("style","background:yellow");
        document.body.insertBefore(srErrDiv, document.body.firstChild);
    }
    GM_log("String resources loaded: "+(SR.loaded==true));

    // define 'en' fallback
    for (var srEntry in SR.en){
        if(srEntry.match(/_[0-9]+$/)) continue; // skip "array" entries "item_1,item_2"
        // GM_log("SR.en."+srEntry+"="+"'"+SR.de[srEntry]+"';");
        if(typeof(SR.de[srEntry])==="undefined")SR.de[srEntry]=SR.en[srEntry];
        if(typeof(SR.fr[srEntry])==="undefined")SR.fr[srEntry]=SR.en[srEntry];
        if(typeof(SR.it[srEntry])==="undefined")SR.it[srEntry]=SR.en[srEntry];
        if(typeof(SR.tr[srEntry])==="undefined")SR.tr[srEntry]=SR.en[srEntry];
        if(typeof(SR.es[srEntry])==="undefined")SR.es[srEntry]=SR.en[srEntry];
        if(typeof(SR.se[srEntry])==="undefined")SR.se[srEntry]=SR.en[srEntry];
        if(typeof(SR.nl[srEntry])==="undefined")SR.nl[srEntry]=SR.en[srEntry];
    }
}
//#endregion multi language string resources (kocpdx.SR.js) 
var ResetAll=false,deleting=false;var ResetTabOptions=false;
var provMapCoords = {imgWidth:710, imgHeight:708, mapWidth:670, mapHeight:670, leftMargin:31, topMargin:19};
var butON='<img align=absmiddle src="%3D" alt="'+culang.buttonON+'">';
var butOFF='<img align=absmiddle src="%3D%3D" alt="'+culang.buttonOFF+'">';
var DEFAULT_ALERT_SOUND_URL = 'http://sfx.god-like.info/airalert.mp3';
var SWF_PLAYER_URL = 'http://kofc.god-like.info/power/swf/pdxminiplayer.swf';
var Options={merlinClose:false,AttackRunning:false,NewTab:false,KsHomeTab:false,NewTabURL:"http://www.your-url.com",NewTabName:"Chat",currentTab:null,currentTab2:"Overview1",reapprointerval:0,TSSrchFilter:0,KsTransparence:true,includeMarching:false,EnableFormation:false,showTroops:true,showPop:false,Smiley:true,showRes:true,SelQG:null,showProduction:true,showDefense:false,encRemaining:true,pbEveryEnable:true,pbEveryMins:60,KDODef:0,pbChatOnRight:false,pbWideMap:false,pbKillFairie:true,maxIdlePop:true,ChatLearder:true,voirRaid:false,WhisperOn:true,gmtClock:false,AttaqueOn:false,WildSoundOn:false,FoodSoundOn:false,EclaireurOn:false,srcSortBy:"level",EnableRefrechRapport:false,srcMinLevel:1,srcMaxLevel:10,srcTypeSelect:1,srcaDist:0,srcDist:20,Xrenfort:0,srcScoutAmt:1,PageReport:1,Yrenfort:0,icon_chatFlag:false,icon_chat:false,URLicon3:"http://kofc.god-like.info/multi/img/pdx-useravatar.png",filPuissance:0,filPuissanceMax:1e6,wildType:1,citySrchFilter:0,fixPageNav:true,mistedOnly:false,hostileOnly:false,fixTower:true,enhanceARpts:true,allowAlterAR:true,enableCheckTournoi:true,HauteurBoite:700,pbWinIsOpen:false,boTrackOpen:true,ptWin2IsOpen:false,ptWinDrag:true,ptWinPos:{},ptWin2Pos:{},enableFoodWarn:true,enableFoodWarnTchat:false,EnableReduireUnit:true,foodWarnHours:24,foodChatWarnHours:4,chatEnhance:true,fixKnightSelect:true,attackCityPicker:true,mapCoordsTop:true,dispBattleRounds:true,reportDeleteButton:true,arPageFrom:1,arPageTo:2,rptType:"alliance",rptAuto:false,alertSound:{enabled:true,soundUrl:DEFAULT_ALERT_SOUND_URL,repeat:true,playLength:20,repeatDelay:.5,volume:100,alarmActive:false,expireTime:0},alertConfig:{changeThrone:false,throneSet:1,returnThrone:false,throneSetRet:1,returnThroneMin:60,aChat:true,raid:false,aPrefix:culang.optionsDefaultAlertMessage,scouting:true,wilds:true,defence:true,minTroops:1,minTroops2:1,embassy:false,fletching:true,marechal:true,defBoost:true,TroneRangeDebuff:false,TroneRange:false,mytroops:false,food:false,defense:true,MonQG:true,hq:"",sendEmail:false,emailAddress:"",token:"",sendasWhisper:false,sendtoAlly:true,showAttack:false,},
    URLson1:"http://sfx.god-like.info/fluestersound.mp3",URLson1Vol:"100",URLson2:"http://sfx.god-like.info/sirene.mp3",URLson2Vol:"100",URLson4:"http://sfx.god-like.info/scouts.mp3",URLson4Vol:"100",URLson5:"http://sfx.god-like.info/phone.mp3",URLson5Vol:"100",URLson6:"http://sfx.god-like.info/phone.mp3",URLson6Vol:"100",multiUpdateSoundEnable:"1",multiUpdateSoundVol:"50",AttackHorloge:"21:00:00",AttackGoHorloge:null,AttackOnOff:false,AttackUnits:{},AttackFav:{0:{0:"200K "+culang.shrmilitiaman+"",1:0,2:2e5,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},1:{0:"200K "+culang.shrheavycavalry+"",1:0,2:0,3:0,4:0,5:0,6:0,7:2e5,8:0,9:0,10:0,11:0,12:0,13:0}},AttackFromCity:0,AttackCibleX:0,AttackCibleY:0,AttackKnight:0,TournoiLigne:25,AttackFSUnits:{1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},5:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},6:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},7:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},8:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},9:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},10:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0}},DeleteMsg:false,DeleteMsgs0:false,DeleteMsgs1:false,DeleteMsgs2:false,DeleteMsgs3:false,DeleteTimerMinute:5,giftDomains:{valid:false,list:{}},giftDelete:"e",HelpRequest:true,ChatRules:false,DeleteRequest:true,MapShowExtra:false,transportinterval:60,minwagons:1e3,lasttransport:0,reassigninterval:60,lastreassign:0,RaidRunning:true,RaidReset:0,MsgInterval:1,foodreport:false,Foodstatus:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    crestRunning:false,Crestinterval:5,CrestSlot:1,crestMarchError:0,CrestMsgInterval:24,Crest1Count:0,Crest2Count:0,crestreport:false,enhancedinbox : true,CrestLevel:0, CrestType:0,Creststatus:{1101:0,1102:0,1103:0,1104:0,1105:0,1106:0,1107:0,1108:0,1109:0,1110:0,1111:0,1112:0,1113:0,1114:0,1115:0,9:0,36:0,37:0,38:0,55:0,57:0,261:0,262:0,271:0,272:0,351:0,361:0,362:0,911:0,3000:0,3001:0,3002:0,3003:0,3007:0,3008:0,3009:0,3011:0,931:0,932:0},LastCrestReport:0,LastReport:0,spamOptions:{enableGlobal:false,spamMessageGlobal:culang.optionsDefaultSpamGlobalMessage,spamMinGlobal:"10",enableAlliance:false,spamMessageAlliance:culang.optionsDefaultSpamAllianceMessage,spamMinAlliance:"10",atimea:0,atime:0},
    EffetRouge:0,AllEffet:false,salvageconfig:{running:false,CityCity:0,RepairCity:0,Repairrunning:false,},TroneInverse:true,pbGoldEnable:false,enhanceViewMembers:true,showMightKoCBugFix : true, showResKoCBugFix : true,showKsInfoBox : false,customWideScreenSize:"1337", enableButtler:true, pdxMenuLeft:false, postMultiUpdate:false, pdxLangFlag:true, pdxHyperlinks:true, reloadIfCrestFaild : true, popupBorderRadius : "0px 0px 0px 0px",
    enableUserName1: false,userName1: "Lord PDX",enableUserName2: false,userName2: "Lady Darren Fohnstone",    enableUserName3     : false,        userName3        : "Lord Thomas Chapin",    enableUserName4     : false,        userName4        : "Lord George Jetson",    enableUserName5     : false,        userName5        : "Lord niknah",    enableUserName6     : false,        userName6        : "Lord DonDavici",    enableUserName7     : false, userName7    : "Lord Nico De Belder",    enableUserName8: false,userName8: "Lord jontey",enableUserName9: false,userName9: "Lord Darren Fohnstone",enableUserName10: false,userName10: "Lord PDX",enableUserName11: false,        userName11        : "Lord PDX",    enableUserName12     : false,        userName12        : "Lady Darren Fohnstone",    enableUserName13     : false,        userName13        : "Lord Thomas Chapin",    enableUserName14     : false,        userName14        : "Lord George Jetson",    enableUserName15     : false,        userName15        : "Lord niknah",    enableUserName16     : false,        userName16        : "Lord DonDavici",    enableUserName17     : false, userName17    : "Lord Nico De Belder",    enableUserName18     : false,        userName18        : "Lord jontey",    enableUserName19     : false,        userName19        : "Lord Darren Fohnstone",    enableUserName20    : false,        userName20        : "Lord PDX",    enableUserName21     : false,        userName21        : "Lord PDX",    enableUserName22     : false,        userName22        : "Lady Darren Fohnstone",    enableUserName23     : false,        userName23        : "Lord Thomas Chapin",    enableUserName24     : false,        userName24        : "Lord George Jetson",    enableUserName25: false,userName25: "Lord niknah",enableUserName26: false,userName26: "Lord DonDavici",    enableUserName27: false, userName27: "Lord Nico De Belder",enableUserName28: false,userName28: "Lord jontey",enableUserName29: false,userName29: "Lord Darren Fohnstone",enableUserName30:false,userName30:"Lord PDX",
    KsFunSoundAttack : false,soundURLF1 : 'http://sfx.god-like.info/war-alarm.mp3',    URLsonF1vol : 100,    
    KsFunSoundHorn : false,soundURLF2 : 'http://sfx.god-like.info/hupenchaos.mp3',     URLsonF2vol : 100,    
    KsFunSoundGun : false,soundURLF3 : 'http://sfx.god-like.info/gun.mp3',     URLsonF3vol : 100,
    reportScanner: {start:false, pages:5, pause:2, lastmsg:0}, inventory: {active:false, item:0},};
var Colors ={ChatLeaders:'#C8C8C8',ChatVC:'#81EE81',ChatChancy:'#F8A151',ChatAtt:'#FF7D7D',ChatAttFont:'#000',ChatWildAtt:'#526F35',ChatWildAttFont:'#000',ChatLowFood:'#6FDB5A',ChatLowFoodFont:'#000',ChatEcl:'#FFDD7D',ChatEclFont:'#000',ChatGlo:'#F9AAAA',ChatGloFont:'#141516',ChatAlliance:'#27D4F0',ChatAllianceFont:'#141516', BGImageURL: 'http://koc-power-pdx.googlecode.com/svn/trunk/img/kocpowerscbg.gif', 
userBG1 : "#333333",    userBG2 : "#584631",    userBG3 : "#FF0000",    userBG4 : "#CCCCFF",    userBG5 : "#CCCCFF",    userBG6 : "#CCCCFF",    userBG7 : "#CCCCFF",    userBG8 : "#CCCCFF",    userBG9 : "#CCCCFF",    userBG10 : "#CCCCFF",    userBG11 : "#333333",    userBG12 : "#584631",    userBG13 : "#FF0000",    userBG14 : "#CCCCFF",    userBG15 : "#CCCCFF",    userBG16 : "#CCCCFF",    userBG17 : "#CCCCFF",    userBG18 : "#CCCCFF",    userBG19 : "#CCCCFF",    userBG20 : "#CCCCFF",    userBG21 : "#333333",    userBG22 : "#584631",    userBG23 : "#FF0000",    userBG24 : "#CCCCFF",    userBG25 : "#CCCCFF",    userBG26 : "#CCCCFF",    userBG27 : "#CCCCFF",    userBG28 : "#CCCCFF",    userBG29 : "#CCCCFF",    userBG30 : "#CCCCFF",
MainTitle:'#FFFFFF', MainTitleHover:'#FF0000',MainTitleBackground: '#600000',MainTitle2:'#FFFFFF',MainTitle2Hover:'#FF0000', MainTitle2Background:'#600000'};
var AttackOptions={LastReport:0,MsgEnabled:true,MsgInterval:60,Method:"distance",SendInterval:8,MaxDistance:50,RallyClip:0,Running:false,BarbsFailedKnight:0,BarbsFailedRP:0,BarbsFailedTraffic:0,BarbsFailedVaria:0,BarbsFailedMarais:0,BarbsFailedBog:0,BarbsTried:0,DeleteMsg:true,DeleteMsgs0:false,Foodstatus:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},MsgLevel:{1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true,9:true,10:true},BarbsDone:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},BarbNumber:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},Levels:{1:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},2:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},3:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},4:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},5:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},6:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},7:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false},8:{0:false,1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false,9:false,10:false}},Troops:{1:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},2:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},3:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},4:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},5:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},6:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},7:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},8:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},9:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0},10:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0,11:0,12:0,13:0}},MinDistance:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0,9:0,10:0},Distance:{1:750,2:750,3:750,4:750,5:750,6:750,7:750,8:750,9:750,10:750},Update:{1:[0,0],2:[0,0],3:[0,0],4:[0,0],5:[0,0],6:[0,0],7:[0,0],8:[0,0]},UpdateEnabled:true,UpdateInterval:30,stopsearch:1,knightselector:0}
var TrainOptions={
    throneCheck:false,
    throneSet:1,
    Running: false,
    list:{},
    Item:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    listactif:{},
    listlabour:{},
    timelauch:60,
    unitemin:{},
    unitemax:{},
    listboost:{},
    UnitMixValue:100,
    Workers:{1:100,2:100,3:100,4:100,5:100,6:100,7:100,8:100},
    Keep:{1:{Food:0,Wood:0,Stone:0,Ore:0},
                2:{Food:0,Wood:0,Stone:0,Ore:0},
                3:{Food:0,Wood:0,Stone:0,Ore:0},
                4:{Food:0,Wood:0,Stone:0,Ore:0},
                5:{Food:0,Wood:0,Stone:0,Ore:0},
                6:{Food:0,Wood:0,Stone:0,Ore:0},
                7:{Food:0,Wood:0,Stone:0,Ore:0},
                8:{Food:0,Wood:0,Stone:0,Ore:0}},
    Resource:{1:true,2:true,3:true,4:true,5:true,6:true,7:true,8:true},
    doTraps:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
    doCalrops:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
    doSpikes:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
    doXbows:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
    doTrebu:{1:false,2:false,3:false,4:false,5:false,6:false,7:false,8:false},
    troopType:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    keepFood:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    keepWood:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    keepStone:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0},
    keepOre:{1:0,2:0,3:0,4:0,5:0,6:0,7:0,8:0}}
var GlobalOptions={updateChatNote:"updateTextImageLike",enableBrowserBG:false,backStyle:"backImg", bgCol: '#222222', bgImg: 'http://koc-power-pdx.googlecode.com/svn/trunk/img/kocpowerscbg.gif', pbWatchdog:false,pbNoMoreKabam:false,pbWideScreen:true,pbWideScreenStyle:"wide",autoPublishGamePopups:false,autoPublishPrivacySetting : 80,escapeurl : null}
var ApothecaryOptions = {Active : false,goldkeep : 0,city : {0:[],1:[],2:[],3:[],4:[],5:[],6:[],7:[]},};
var CombatOptions={research:[{tch8:0,tch9:0,tch13:0,tch15:0},{tch8:0,tch9:0,tch13:0,tch15:0}],knt:[50,50],guardian:[["wood",0],["ore",0]],ratio:[{unt1:{},unt2:{},unt3:{},unt4:{},unt5:{},unt6:{},unt7:{},unt8:{},unt9:{},unt10:{},unt11:{},unt12:{}},{unt1:{},unt2:{},unt3:{},unt4:{},unt5:{},unt6:{},unt7:{},unt8:{},unt9:{},unt10:{},unt11:{},unt12:{}}]}
var CrestOptions = {
    Running       :     false,
    CrestCity     :     0,
    RoundOne      :     false,
    RoundTwo      :     true,
    lastRoundTwo     :     0,
    X                :    0,
    Y                :    0,
    R1ST            :    0,
    R1MM            :    0,
    R1Scout        :    0,
    R1Pike        :    0,
    R1Sword        :    0,
    R1Arch        :    0,
    R1LC            :    0,
    R1HC            :    0,
    R1SW            :    0,
    R1Ball        :    0,
    R1Ram            :    0,
    R1Cat            :    0,
    R1BT            :    0,
    R1EX            :    0,
    R1SWa            :    0,
    R2ST            :    0,
    R2MM            :    0,
    R2Scout        :    0,
    R2Pike        :    0,
    R2Sword        :    0,
    R2Arch        :    0,
    R2LC            :    0,
    R2HC            :    0,
    R2SW            :    0,
    R2Ball        :    0,
    R2Ram            :    0,
    R2Cat            :    0,
    R2BT            :    0,
    R2EX            :    0,
    R2SWa            :    0,
};

var CrestData = new Array();
function CrestFunc (Arr) {
    if (Arr == undefined)
        Arr = CrestOptions;

    this.Running         =      true;
    this.active         =      Arr.active;
    this.CrestCity         =     Arr.CrestCity;
    this.RoundOne         =     Arr.RoundOne;
    this.RoundTwo         =     true;
    this.lastRoundTwo     =     0;
    this.X                 =     Arr.X;
    this.Y                 =     Arr.Y;
    this.R1ST             =     Arr.R1ST;
    this.R1MM             =     Arr.R1MM;
    this.R1Scout         =     Arr.R1Scout;
    this.R1Pike         =     Arr.R1Pike;
    this.R1Sword         =     Arr.R1Sword;
    this.R1Arch         =     Arr.R1Arch;
    this.R1LC             =     Arr.R1LC;
    this.R1HC             =     Arr.R1HC;
    this.R1SW             =     Arr.R1SW;
    this.R1Ball         =     Arr.R1Ball;
    this.R1Ram             =     Arr.R1Ram;
    this.R1Cat             =     Arr.R1Cat;
    this.R1BT             =     Arr.R1BT;
    this.R1EX             =     Arr.R1EX;
    this.R1SWa             =     Arr.R1SWa;
    this.R2ST             =     Arr.R2ST;
    this.R2MM             =     Arr.R2MM;
    this.R2Scout         =     Arr.R2Scout;
    this.R2Pike         =     Arr.R2Pike;
    this.R2Sword         =     Arr.R2Sword;
    this.R2Arch         =     Arr.R2Arch;
    this.R2LC             =     Arr.R2LC;
    this.R2HC             =     Arr.R2HC;
    this.R2SW             =     Arr.R2SW;
    this.R2Ball         =     Arr.R2Ball;
    this.R2Ram             =     Arr.R2Ram;
    this.R2Cat             =     Arr.R2Cat;
    this.R2BT             =     Arr.R2BT;
    this.R2EX             =     Arr.R2EX;
    this.R2SWa             =     Arr.R2SWa;
};
var upgradeData = {  active : false, Items: [],  retryInterval : 30, };
var ThroneOptions = {
    Active:false,
    IntervalMin:3,
    Interval:30,
    RepairTime:0,
    Tries:0,
    minStones : 100000,
    Good:0,
    Bad:0,
    Items: [],
    CityMax: false,
    i20001: false, //Rune des geringen Schutzes
    i20002: false, //Schutzrune
    i20004: false, //Rune der Alchemie
    i20005: false, //Rune des geringen Gluecks
    i20006: false, //Gluecksrune
    RepairAll: false,
    SalvageV2:{
        SaveXitems:0,
        QualityFilter:0,
        TypeFilter:{Advisor:true,Banner:true,Chair:true,Table:true,Window:true, Trophy:true, Candelabrum:true},
        EffectMode:0,EffectMode2:100,EffectMode3:100,
        EffectFilter:{},
        Preview:{ShowDel:true,ShowKeep:false},
        DeleteXitems:{IsEnabled:false,Value:3}, //v2.0.6b2
        LevelP1: false,
        CityMin: false,
    },
}; //EffectFilter:{}, // {Name:{IsEnabled,IsEnabled2,IsEnabled3,Percent},...}
var FarmOptions = {
    RallyClip: 0,
    Running: false,
    MinMight: 0,
    MaxMight: 999999999,
    Interval: 0,
    SendInterval: 10,
    MaxDistance: 20,
    Inactive:30,
    DeleteReports:false,
    Troops: {1: 0,2: 0,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0,9: 0,10: 0,11: 0,12: 0,13:0,14:0,15:0},
    FarmNumber: {1: 0,2: 0,3: 0,4: 0,5: 0,6: 0,7: 0,8: 0},
    CityEnable: {1: true,2: true,3: true,4: true,5: true,6: true,7: true,8: true},
    CityLevel: {0: true,1: true,2: true,3: true,4: true,5: true,6: true,7: true,8: true,9: true,10: true,11: true,12: true},
    Diplomacy: {friendly: true,hostile: true,friendlyToThem: true,friendlyToYou: true,neutral:true,unallied:true},
    FarmMarches: [],
    farmMarches: {},
    Attacks:0,
    Checks:0,
};
var TabOptions = {
    toOverview : 1,
    toReports : 2,
    toMarches : 3,
    toTrain : 4,
    toAutoTrain : 5,
    toThroneStuff : 6,
    toSearch : 7,
    toPlayer : 8,
    toBuild : 9,
    toTransport : 10,
    toReassign : 11,
    toAutoCraft : 12,
    toFarm : 13,
    toCrest : 14,
    toDarkForest : 15,
    toRaid : 16,
    toApothecary : 17,
    toScoutAlliance : 18,
    toWild : 19,
    toKnights : 20,
    toOptions : 21,
    toUserTab : 22,
    toKoCScripts : 23,
};
var KsRange = {
    rb    : 0,
    rdb   : 0,
    sb    : 0,
    sdb   : 0,
    rrb   : 0,
    rrdb  :    0,
    orb   :    0,
    ordb  :    0,
    osb   :    0,
    osdb  :    0,
    orrb  :    0,
    orrdb :    0,
};

var avatars = {};
eval(GM_getResourceText("PLUGIN_AVATAR"));
var Smileys = {};
eval(GM_getResourceText("PLUGIN_SMILEYS"));

 

if (!releaseVersion) {
    var KsScriptRunning = ""+culang.optionsBeta+"";
    var KsScriptPage = "http://code.google.com/p/mad-hatters-magic/";
    var KsInstallLink = "http://mad-hatters-magic.googlecode.com/svn/release/E_M_H-powered.user.js";
    var KsLangpackFolder = "http://koc-power-pdx.googlecode.com/svn/beta/langpacks/";
    var KsLatestVersion = ""+culang.optionsLatestInstall+" <a href='http://mad-hatters-magic.googlecode.com/svn/release/E_M_H-powered.user.js' target='_blank' title='"+culang.optionsLatestReleaseInstallNote+"'>"+culang.optionsRelease+"</a> "+culang.mainVersion+" <a href='http://mad-hatters-magic.googlecode.com/svn/release/E_M_H-powered.user.js' target='_blank' title='"+culang.optionsLatestReleaseInstallNote2+"'>"+culang.optionsLatestInstall2+"</a>";
} else {
    var KsScriptRunning = ""+culang.optionsRelease+"";
    var KsScriptPage = "http://code.google.com/p/mad-hatters-magic/";
    var KsInstallLink = "http://mad-hatters-magic.googlecode.com/svn/release/E_M_H-powered.user.js";
    var KsLangpackFolder = "http://koc-power-pdx.googlecode.com/svn/release/"+KsLangpackFolderId+"/langpacks/";
    var KsLatestVersion = ""+culang.optionsLatestInstall+" <a href='http://code.google.com/p/mad-hatters-magic/' target='_blank' title='"+culang.optionsLatestBetaInstallNote+"'>"+culang.optionsBeta+"</a> "+culang.mainVersion+" <a href='http://mad-hatters-magic.googlecode.com/svn/release/E_M_H-powered.user.js' target='_blank' title='"+culang.optionsLatestBetaInstallNote2+"'>"+culang.optionsLatestInstall2+"</a>";
}
readOptions();
function $(ID,root) {return (root||document).getElementById(ID);}
var nHtml={FindByXPath:function(a,b,c){if(!c){c=XPathResult.FIRST_ORDERED_NODE_TYPE}try{var d=document.evaluate(b,a,null,c,null)}catch(e){GM_log("bad xpath:"+b)}if(c==XPathResult.FIRST_ORDERED_NODE_TYPE){if(d&&d.singleNodeValue){return d.singleNodeValue}}else{if(d){return d}}return null},ClickWin:function(a,b,c){var d=a.document.createEvent("MouseEvents");d.initMouseEvent(c,true,true,a,0,0,0,0,0,false,false,false,false,0,null);return!b.dispatchEvent(d)},Click:function(a){return this.ClickWin(window,a,"click")},ClickTimeout:function(a,b){window.setTimeout(function(){return nHtml.ClickWin(window,a,"click")},b+Math.floor(Math.random()*500))},SetSelect:function(a,b){for(var c=0;c<a.options.length;c++){if(b==a.options[c].value){a.options[c].selected=true;return true}}return false}}
function ById(id) {return document.getElementById(id);}
if (document.URL.search(/kingdomsofcamelot.com\/fb\/e2\/src\/helpFriend_src.php/i) >= 0){ helpFriends (); return true;} //TODO Warnung: [KoCPower-Multilang@PDX] "return" aus dem Haupt-Scope wird normalerweise nicht unterstuetzt. Sie sollten dies im Benutzerskript beheben.
readGlobalOptions();
if (document.URL.search(/apps.facebook.com\/kingdomsofcamelot/i) >= 0){
    setTimeout(function() {
        var test=document.URL;
        var testt = /s=([0-9]+)/i.exec(test);
        if (testt) {
            unsafeWindow.window.document.title=""+ScriptName+" "+Version+" - ("+testt[1]+")";
        }
    }, 10000)
    facebookInstance ();
    return;
}

if (document.URL.search(/kingdoms-of-camelot\/play/i) >= 0){ kabamStandAlone(); return;}
if (document.URL.search(/facebook.com/i) >= 0){ if(document.URL.search(/connect\/uiserver.php/i) >= 0 || document.URL.search(/serverfbml/i) >= 0 || document.URL.search(/dialog\/stream.publish/i) >= 0 || document.URL.search(/dialog\/apprequests/i) >= 0 || document.URL.search(/dialog\/feed/i) >= 0) HandlePublishPopup ();return;}
if (document.URL.search(/kingdomsofcamelot.com/i) >= 0){kocWideScreen ();}

function helpFriends(){function a(){var b=ById("claimhelpform");if(!b){setTimeout(a,1e3)}b.submit()}a()}
function readGlobalOptions (){
    s = GM_getValue ('KsOptions_??');
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts)
            GlobalOptions[k] = opts[k];
    }
}
function kocWideScreen(){
    var fois=0;
    function setWideFb (){
        var kocFrame = parent.document.getElementById('kocIframes1'); //TODO Fehler: [KoCPower-Multilang@PDX] Error: Permission denied to access property 'document'
        if (!kocFrame){
            setTimeout (setWideFb, 1000);
            return;
        }
        kocFrame.style.width = '100%';
        var style = document.createElement('style');
        style.innerHTML = 'body { margin:0; width:100%; !important;}';
        kocFrame.parentNode.appendChild(style);
    
    }
    function test() {
        var alla = ById('kocinitloading');
        if (alla) {
            if (alla.style.display!="none") {
                fois++;
                if (fois>23)  reloadKOC();
                setTimeout (test, 2500);
                return;
            }
        }
    }
    if(document.URL.match(/standalone=0/i)){
        test();
    }
    kocWatchdog ();
    if (GlobalOptions.pbWideScreen)
        setWideFb();
}

function kabamStandAlone  (){
    function setWide (){
        var iFrames = ById('game_frame');
        if (!iFrames){
            setTimeout (setWide, 1000);
            return;
        }
        iFrames.style.width = '100%';
        while ( (iFrames=iFrames.parentNode) != null)
            if (iFrames.tagName=='DIV')
                iFrames.style.width = '100%';
        ById("main-nav").parentNode.removeChild(ById("main-nav"));
        ById("main-header").parentNode.removeChild(ById("main-header"));
        ById("promo-sidebar").style.display = "none";                
try {
        if (GlobalOptions.enableBrowserBG && GlobalOptions.backStyle=="backCol") ById("content" && "gameIframe").style.backgroundColor= GlobalOptions.bgCol;
} catch (e) {}
try {
        if (GlobalOptions.enableBrowserBG && GlobalOptions.backStyle=="backImg")  ById("content" && "gameIframe").style.backgroundImage = "url('"+GlobalOptions.bgImg+"')";
} catch (e) {}
    }
    function sendmeaway (){
        var serverID = /s=([0-9]+)/im.exec (document.location.href);
        var sr = /signed_request" value="(.*?)"/im.exec ($("post_form").innerHTML);
        var goto = $("post_form").action+(serverID?"?s="+serverID[1]:'');
        var t = '<FORM target="_top" action="'+ goto +'" method=post><INPUT id=xxxpbutExplode type=submit value=RELOAD><INPUT type=hidden name=signed_request value="'+ sr[1] +'" /><INPUT type=hidden name=platform_req value=A /></form>';
        var e = document.createElement ('div');
        e.innerHTML = t;
        document.body.appendChild (e);
        setTimeout (function (){document.getElementById('xxxpbutExplode').click();}, 0);
    }
    if (GlobalOptions.pbWideScreen)
        setWide();
    if(GlobalOptions.pbNoMoreKabam)
        sendmeaway();

}

function facebookInstance(){function a(){var b=ById("iframe_canvas");if(!b){setTimeout(a,1e3);return}b.style.width="100%";while((b=b.parentNode)!=null)if(b.tagName=="DIV")b.style.width="100%";ById("globalContainer").style.left="0px";try{ById("rightCol").parentNode.removeChild(ById("rightCol"));ById("leftColContainer").parentNode.removeChild(ById("leftColContainer"))}catch(c){}
    var c=ById("mainContainer");if(c){if(GlobalOptions.pbWideScreenStyle=="normal")c.parentNode.style.minWidth="100%";var pied = ById('pagelet_canvas_footer_content');if(pied) { pied.parentNode.removeChild(pied); }if(GlobalOptions.pbWideScreenStyle=="wide")c.parentNode.style.width="1520px";if(GlobalOptions.pbWideScreenStyle=="ultra")c.parentNode.style.width="2000px";if(GlobalOptions.pbWideScreenStyle=="custom")c.parentNode.style.width=""+Options.customWideScreenSize+"px";for(i=0;i<c.childNodes.length;i++){if(c.childNodes[i].id=="contentCol"){c.childNodes[i].style.margin="0px";c.childNodes[i].style.paddingTop="0px";if (GlobalOptions.enableBrowserBG && GlobalOptions.backStyle=="backCol") c.childNodes[i].style.backgroundColor= GlobalOptions.bgCol;if (GlobalOptions.enableBrowserBG && GlobalOptions.backStyle=="backImg")  c.childNodes[i].style.backgroundImage = "url('"+GlobalOptions.bgImg+"')";break;}}}var c=ById("pageHead");if(c){c.style.width="80%";c.style.margin="0 10%"}var c=ById("bottomContent");if(c){c.style.padding="0px 0px 12px 0px"}}facebookWatchdog();if(GlobalOptions.pbWideScreen)a()}
function HandlePublishPopup() {
    if(GlobalOptions.autoPublishGamePopups){
        var FBInputForm = document.getElementById('uiserver_form');
        if(FBInputForm){
            var channel_input = nHtml.FindByXPath(FBInputForm,".//input[contains(@name,'channel')]");
            if(channel_input){
                var current_channel_url = channel_input.value;
                if (current_channel_url.match(/(http|https):\/\/(.*?)\.kingdomsofcamelot\.com(.*?)/i)) {
                    var publish_label = document.getElementById('publish');
                    var publish_button = nHtml.FindByXPath(publish_label,".//input[@type='submit']");
                    var privacy_setting = nHtml.FindByXPath(FBInputForm,".//select[@name='audience[0][value]']");
                    if(publish_button && privacy_setting){
                        privacy_setting.innerHTML = '<option value="'+ GlobalOptions.autoPublishPrivacySetting +'"></option>';
                        privacy_setting.selectedIndex = 0;
                        nHtml.Click(publish_button);
                    }
                }
            }
        }
        setTimeout(HandlePublishPopup, 1000);
    }
}

function facebookWatchdog(){function b(){try{if(ById("app_content_130402594779")==null){logit("KOC NOT FOUND!");KOCnotFound(5*60)}}catch(a){logit("KOC NOT FOUND!");KOCnotFound(4*60)}}var a=5e4;if(!GlobalOptions.pbWatchdog)return;setTimeout(b,a)}
function kocWatchdog(){function b(){if(ById("mod_maparea")==null && ById("click")==null){logit("KOC not loaded");KOCnotFound(20)}}var a=1e4;if(!GlobalOptions.pbWatchdog)return;setTimeout(b,a)}
readOptions();
var Cities = {};
var Seed = unsafeWindow.seed;
var uW = unsafeWindow;
var CM = unsafeWindow.cm;
var Tabs = {};
var my = {};
var Tabs2 = {};
var researchLevels = [];
var researchLevels2 = [];
var crestname = {};
// var CPopUpTopClass = 'ksPopTop';
var mainPop, mainPop2;
var ResetColors = false;
var Tabs2=[["Movement",culang.tabLabelMovement],["Throne",culang.tabLabelThrone],["Overview",culang.tabLabelProduction],["Stock",culang.mainInventory],["Info",culang.mainInfo],["Alliance",culang.tabLabelAlliance],["Tournament",culang.tabLabelTournament],["Gifts",culang.mainGifts],["Resources",culang.tabLabelCourt],["Combat",culang.tabLabelCombat],["Spam","Spam"],["Fake",culang.tabLabelFake],["ActionLog",culang.tabLabelActionLog]]; 
var KsStartupTimer = null;
ptStartupErrorTimer = null;
var currentName2 = 'Movement';
var myServerId = null;
var LastUnixTime = null;
function getServerId(){if(myServerId==null){var a=/^[a-zA-Z]+([0-9]+)\./.exec(document.location.hostname);if(a)myServerId=a[1];else myServerId="??"}return myServerId}

function pdxStartup (){

    clearTimeout (KsStartupTimer);
    if (unsafeWindow.KsLoaded)
        return;
    var metc = getClientCoords(ById('main_engagement_tabs'));
    if (metc.width==null || metc.width==0){
        KsStartupTimer = setTimeout (pdxStartup, 1000);
        return;
    }
    unsafeWindow.KsLoaded = Version;
    readOptions();readColors();readTabOptions();//readLanguage();

    var showKsInfoBox = '.pdxInfoBox { background-image:url('+IMGksBG+'); font-variant:small-caps; padding: 8px; border-radius: 5px;  -moz-box-shadow: 0 0 2px 2px #141516; color: #FFFFFF;  max-height: 160px; width: 300px; margin-top:5px; } .pdxInfoBox a {color:#FFF; top:-2px; transition-duration: 0.2s; -moz-transition-duration: 0.2s; -webkit-transition-duration: 0.2s; -o-transition-duration: 0.2s;} .pdxInfoBox a:hover { color: #FF0000; margin-left: 2px;  box-shadow: 1px 1px 2px 0px #FF0000; padding: 0px 3px 0px 3px; }';
    var showMightKoCBugFix  = '';
    if (Options.showMightKoCBugFix) var showMightKoCBugFix = '#mainbody div#kochead.kocHeader div.taskbar div.rightColumn div.avatarInfo div.avatarStats div.avatarGlory { margin-left:30px; } .kocHeader .avatarStats .avatarLevel { padding-top:1px; left: -2px;  top: 35px;} .kocHeader .avatarMight, .kocHeader .avatarGlory {padding-left:1px;}';
    var showResKoCBugFix  = '';
    if (Options.showResKoCBugFix) var showResKoCBugFix = '.kocmain .mod_cityinfo #cityinfo_1 table .grw {left: 650px;    margin-top: 25px;    position: fixed;    text-align: right;    width: 60px;} .kocmain .mod_cityinfo #cityinfo_1 table tbody tr td {    background-color: transparent;    border-bottom: 1px solid transparent;}';

    Seed = unsafeWindow.seed;
    GM_addStyle ('.xtab {padding-right: 5px; border:none; background:none; white-space:nowrap;}\
    .tournamentTable { padding: 10px; border-radius:5px; border: 1px outset #141516; background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee;    box-shadow: 2px 2px 2px 2px #eee; }\
    .'+culang.kocHostile+' td { background:crimson; }.'+culang.kocFriendly+' td{background:lightblue; }.'+culang.kocAllys+' td{background:royalblue; }\
    .'+culang.kocNeutral+' td { background:lightgreen; }.'+culang.kocNoAlliance+' td { background:gold; }\
    .xtabBR {padding-right: 5px; border:none; background:none;}\
    .buttonHelp {padding:1px; height:15px;font-size:9px;font-weight:bold; background-color:green;border-radius:5px; border: 1px outset #141516; }\
    .buttonHelp:hover {background-color:gray;}\
    div.ptDiv {background-color:none;}\
    table.pdxTab tr td {border:none; background:none; white-space:nowrap;}\
    table.ptTabPad tr td {border:none; background:none; white-space:nowrap; padding: 2px 4px 2px 8px;}\
    table.ptTabBR tr td {border:none; background:none;}\
    table.ksTabLined tr td {border:1px none none solid none; padding: 2px 5px; white-space:nowrap;}\
    table.ptTabPad tr td.pdxEntry {background-color:#ffeecc; padding-left: 8px;}\
    table.pdxTabOverview tr td {border-left:1px solid #ccc; white-space:nowrap; padding: 1px;   font-size:11px;}\
    table.ptNoPad tr td {border:none; background:none; white-space:nowrap; padding:0px}\
    .ptOddrow {background-color:#eee}\
    .pdxStatOverview {border: 0.5px inset #ffffff; border-radius:5px; -moz-box-shadow: inset 0px 0px 2px #ffffff; font-weight:bold; font-size:12px; font-variant:small-caps;   padding:3px; text-align:center; color:'+Colors.MainTitle+';    background-color:'+Colors.MainTitleBackground+';}\
    .pdxStat {border: 0.5px inset #ffffff; border-radius:10px 10px 5px 5px; -moz-box-shadow: 2px 2px 2px 2px #EEEEEE; font-weight:bold; font-size:14px; font-variant:small-caps;  padding:0px 10px; text-align:center; color:'+Colors.MainTitle+';    background-color:'+Colors.MainTitleBackground+'; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
    .pdxStat a { font-weight:bold; font-size:14px; color:'+Colors.MainTitle+';  font-variant:small-caps;  text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000;  text-decoration: none; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
    .pdxStat a:hover { font-size:15px; color:'+Colors.MainTitleHover+'; text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000; }\
    .pdxStat2 {border: 0.5px inset #ffffff;  border-radius:10px 10px 5px 5px; -moz-box-shadow: 2px 2px 2px 2px #EEEEEE; font-weight:bold; font-size:11px; font-variant:small-caps;  padding:0px 10px; text-align:center; color:'+Colors.MainTitle2+';    background-color:'+Colors.MainTitle2Background+'; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
    .pdxStat2 a { font-weight:bold; font-size:11px; color:'+Colors.MainTitle2+';  font-variant:small-caps;  text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000;  text-decoration: none; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
    .pdxStat2 a:hover { font-size:12px; color:'+Colors.MainTitle2Hover+';  text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000; }\
    .pdxEntry {padding: 7px; border:1px solid; border-color:#000000; background-color:#ffeecc; white-space:nowrap;}\
    .ptErrText {font-weight:bold; color:#600000}\
    .pdxStatLight {font-weight:bold;  font-variant:small-caps;  padding:0px 10px; text-align:center; color:'+Colors.MainTitle+';     -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
    .pdxStatLight a {font-weight:bold;  color:'+Colors.MainTitle+';  font-variant:small-caps;  text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000;  text-decoration: none; -webkit-transition: all 1sease;-moz-transition: all 1sease;-o-transition: all 1sease;transition: all 1sease;}\
    .pdxStatLight a:hover { font-size:11px; color:'+Colors.MainTitleHover+'; text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000; }\
    button::-moz-focus-inner, input[type="submit"]::-moz-focus-inner { color:#FFFFFF; border: none; border-radius:5px; }\
    input[type="text"] { padding: 1px; border: 0.5px inset #141516;   }\
    input[type="button"],input[type="submit"] { border: 1px outset #141516;  border-radius:3px; }\
    input[type="submit"]:hover,input[type="button"]:hover  { color: #600000; background-color:#FFFFFF; }\
    .ptChatWhisper {}\
    .ptChatLowFood {color: '+Colors.ChatLowFoodFont+'; font-weight:bold; background-color: '+Colors.ChatLowFood+'; }\
    .ptChatWildAttack {color: '+Colors.ChatWildAttFont+'; font-weight:bold; background-color: '+Colors.ChatWildAtt+'; }\
    .ptChatAttack {color: '+Colors.ChatAttFont+'; font-weight:bold; background-color: '+Colors.ChatAtt+'; }\
    .ptChatScout {color: '+Colors.ChatEclFont+'; font-weight:bold; background-color: '+Colors.ChatEcl+'; }\
    .ptChatAlliance {}\
    .ptChatGlobal {background-color: #fdd}\
    .ptChatIcon {border: 1px inset red; border-radius:3px;}\
    .ptChatScripter {font-weight:bold;}\
    .ptChatCHAN {color:#000; background-color:'+Colors.ChatChancy+';}\
    .ptChatVICE {color:#000; background-color:'+Colors.ChatVC+';}\
    .ptChatOFFI {color:#000; background-color:'+Colors.ChatLeaders+';}\
    input.defButtonOn { cursor:pointer; border:1px solid black; background-color:red;}\
    input.defButtonOff { cursor:pointer; border:1px solid black; background-color:#0a0;}\
    span.whiteOnRed {padding-left:3px; padding-right:3px; background-color:#700; color:white; font-weight:bold}\
    span.boldRed {color:#800; font-weight:bold}\
    span.boldDarkRed {color:#600; font-weight:bold}\
    span.boldGreen {color:green; font-weight:bold}\
    span.helpText {color:#555555; font-style:italic; font-size:9px;}\
    span.helpTextImp {color:#600000; font-style:italic; font-size:11px;}\
    span.shadowCaps {color:#0000; font-weight:bold;text-shadow: 1px 1px 1px #AAA; font-variant:small-caps; text-align:center}\
    span.logTime {font-size: 9px; color:#141516; text-align:center}\
    span.shadowCapsItalic {color:#0000; font-style:italic;text-shadow: 1px 1px 1px #AAA; font-variant:small-caps; text-align:center}\
    .emoicon {width:19px !important;height:19px !important;float:none !important;}\
    .castleBut {outline:0px; margin-left:0px; margin-right:0px; width:24px; height:26px; font-size:12px; font-weight:bold;}\
    .castleBut:hover {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}\
    .castleButNon {background-image:url("'+ URL_CASTLE_BUT +'")}\
    .castleButSel {background-image:url("'+ URL_CASTLE_BUT_SEL +'")}\
    a.ptButton20 {color:#ffff80}\
    input.ksMSubtab {cursor:pointer; width:10em; margin-right:15px;}\
    input.ksMSubtabSel {background-color:#444444; color:white; font-weight:bold; cursor:none !important}\
    input.ptButCancel { background-color:#a00; font-weight:bold; color:#fff}\
    multiTab {}\
    table.mulltiMainTabs { empty-cells: show;  margin-left: 5px;  margin-top: 4px; padding: 1px; }\
    .ksTabSel {  font-weight:bold; font-variant:small-caps; color : #2F230E; white-space: nowrap; cursur:pointer; height: 17px;   }\
    .ksTabSel span {  color : #2F230E; background: url("'+IMGtabSelected+'"); display: inline-block; width: 78px;   height: 16px;    padding: 1px 7px;    text-decoration: none;   }\
    .ksTabNotSel { font-weight:500;  font-variant:small-caps; color: #2F230E; white-space: nowrap; cursur:pointer; height: 17px; }\
    .ksTabNotSel span {  color : #2F230E; background: url("'+IMGtabNoSelect+'"); display: inline-block; width: 78px;  height: 16px;    padding: 1px 7px;    text-decoration: none;   }\
    .ksTabSelLeft {  font-weight:bold; font-variant:small-caps; color : #2F230E; white-space: nowrap; cursur:pointer; height: 17px;   }\
    .ksTabSelLeft span {  color : #2F230E;  width: 78px;   height: 16px;    padding: 1px 7px;    text-decoration: none;   }\
    .ksTabNotSelLeft { font-weight:500;  font-variant:small-caps; color: #2F230E; white-space: nowrap; cursur:pointer; height: 17px; }\
    .ksTabNotSelLeft span {  color : #2F230E;  width: 78px;  height: 16px;    padding: 1px 7px;    text-decoration: none;   }\
    tr.ksCPopupTop td { border:none; height: 15px;  padding:0px; background:none;}\
    .Ksptretry_top { background-color:#a00; color:#fff; border:none; height: 21px; padding:0px; }\
    .popupBanner { margin-bottom:10px; height:25px; background-color:#600000; text-align:center;font-size: 20px; font-weight:bold; font-variant:small-caps; color:#FFFFFF; text-shadow: -1px -1px 0px #141516, 1px 1px 0px #600000;  border:1px inset #141516;      border-radius:14px;  -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee;    box-shadow: 2px 2px 2px 2px #eee;}\
    .ksCPopup .ksCPopMain {  opacity:0.9;overflow:auto;border:none; background:none; }\
    .idp_CPopup .idp2_CPopup { opacity:0.9; }\
    #ksQuick.tabs_engagement span center b a {color:#FFFFFF;}\
    #ksQuick.tabs_engagement span center b a:hover {color:#FF0000;}\
    .ptChatUser1 {background-color: '+ Colors.userBG1 +';}        .ptChatUser2 {background-color: '+ Colors.userBG2 +';}    .ptChatUser3 {background-color: '+ Colors.userBG3 +';}    .ptChatUser4 {background-color: '+ Colors.userBG4 +';}    .ptChatUser5 {background-color: '+ Colors.userBG5 +';}    .ptChatUser6 {background-color: '+ Colors.userBG6 +';}    .ptChatUser7 {background-color: '+ Colors.userBG7 +';}    .ptChatUser8 {background-color: '+ Colors.userBG8 +';}    .ptChatUser9 {background-color: '+ Colors.userBG9 +';}    .ptChatUser10 {background-color: '+ Colors.userBG10 +';}    .ptChatUser11 {background-color: '+ Colors.userBG11 +';}        .ptChatUser12 {background-color: '+ Colors.userBG12 +';}    .ptChatUser13 {background-color: '+ Colors.userBG13 +';}    .ptChatUser14 {background-color: '+ Colors.userBG14 +';}    .ptChatUser15 {background-color: '+ Colors.userBG15 +';}    .ptChatUser16 {background-color: '+ Colors.userBG16 +';}    .ptChatUser17 {background-color: '+ Colors.userBG17 +';}    .ptChatUser18 {background-color: '+ Colors.userBG18 +';}    .ptChatUser19 {background-color: '+ Colors.userBG19 +';}    .ptChatUser10 {background-color: '+ Colors.userBG20 +';}    .ptChatUser21 {background-color: '+ Colors.userBG21 +';}        .ptChatUser22 {background-color: '+ Colors.userBG22 +';}    .ptChatUser23 {background-color: '+ Colors.userBG23 +';}    .ptChatUser24 {background-color: '+ Colors.userBG24 +';}    .ptChatUser25 {background-color: '+ Colors.userBG25 +';}    .ptChatUser26 {background-color: '+ Colors.userBG26 +';}    .ptChatUser27 {background-color: '+ Colors.userBG27 +';}    .ptChatUser28 {background-color: '+ Colors.userBG28 +';}    .ptChatUser29 {background-color: '+ Colors.userBG29 +';}    .ptChatUser10 {background-color: '+ Colors.userBG30 +';}\
    '+showMightKoCBugFix+'\
    '+showResKoCBugFix+'\
    '+showKsInfoBox+'\
    ');
    setCities();readTrainingOptions();readCrestData();readAttackOptions();readFarmOptions();readThroneOptions();readApothecaryOptions();readCombatOptions();readKsRange();
    CM.cheatDetector.detect = foo;
    if (Options.ptWinPos==null || Options.ptWinPos.x==null|| Options.ptWinPos.x=='' || isNaN(Options.ptWinPos.x)){
        var c = getClientCoords (ById('main_engagement_tabs'));
        Options.ptWinPos.x = c.x+4;
        Options.ptWinPos.y = c.y+c.height;
        saveOptions ();
    }
    if (Options.ptWin2Pos==null || Options.ptWin2Pos.x==null|| Options.ptWin2Pos.x=='' || isNaN(Options.ptWin2Pos.x)){
        var c = getClientCoords (ById('main_engagement_tabs'));
        Options.ptWin2Pos.x = c.x+4;
        Options.ptWin2Pos.y = c.y+c.height;
        saveOptions ();
    }
    if(!GlobalOptions.pbWideScreen && Options.ptWinPos.x > 700){
        var c = getClientCoords (ById('main_engagement_tabs'));
        Options.ptWinPos.x = c.x+4;
        saveOptions ();
    }
    var hauteur=parseIntNan(Options.HauteurBoite) + 30;
    mainPop = new CPopup ('idp1', Options.ptWinPos.x, Options.ptWinPos.y, 800, hauteur, Options.ptWinDrag,
        function (){
            tabManager.hideTab();
            Options.pbWinIsOpen=false;
            saveOptions()
        });
    var mainDiv = mainPop.getMainDiv();
    mainPop.getTopDiv().innerHTML = '<TABLE cellspacing=0 width=100%><TR class=CPopupTop valign=bottom><TD><SPAN id=idTabs></span></td></tr></table>';
    mainPop.autoWidth(true);

    AddMainTabLink("<IMG height='36' src='"+IMGbuttonPower+"' alt='POWER' title='KoC Power - Main Tabs'>", eventHideShow, mouseMainTab);
    tabManager.init (mainPop.getMainDiv());
    TowerAlerts.init();
    AllianceReports.init ();
    DispReport.init();
    messageNav.init();
    RefreshEvery.init();
    ChatStuff.init ();
    battleReports.init ();
    AttackDialog.init();
    ChatPane.init();
    CoordBox.init();
    Tabs.Rpt.AutoStart();

    if (!ThroneOptions.Active) {
        setTimeout(function() { RepairAuto.init (); },15000);
    } else {
        Options.salvageconfig.Repairrunning=false;
    }

    setTimeout(function() {
        DeleteReports.init();
        exportToKOCattackKs.init();
        SpamEvery.init ();
        SpamEveryA.init ();
        CollectGold.init();
        FairieKiller.init (Options.pbKillFairie);
        FoodAlerts.init();
    },60000); // on attends 60 sec avant le lancement de certains fonction
    if (Options.pbWinIsOpen){
        mainPop.show (true);
        tabManager.showTab();
    }

    window.addEventListener('unload', onUnload, false);
    TowerAlerts.setPostToChatOptions(Options.alertConfig);
    AddMainTabLink2("<IMG height='36' src='"+IMGbuttonQuick+"'  alt='QUICK' title='KoC Power - Quick Tabs'>", eventHideShow2, mouseMainTab2);
    WideScreen.init ();
    WideScreen.setChatOnRight (Options.pbChatOnRight);
    WideScreen.useWideMap (Options.pbWideMap);
    gmtClock.init();

    var params=unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);params.format=2;params.tournyPos=0;new AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/getLeaderboard.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,onSuccess:function(transport){var rslt=eval("("+transport.responseText+")");if(rslt.ok){if(rslt.data){ById("pdxTabs2").innerHTML='<IMG alt="'+culang.mainTournament+'" height="36" src="'+IMGbuttonQuickTournament+'" title="'+culang.mainTournament+'">';}}}})

    if (Options.currentTab2) {
        currentName2 = Options.currentTab2;
        if (currentName2=='Overview1')  currentName2 = 'Movement';
        if (currentName2=='map')  currentName2 = 'Movement';
        if (currentName2=='build')  currentName2 = 'Movement';
        if (currentName2=='AutoTrain') currentName2 = 'Movement';
    } else {
        currentName2 = 'Movement';
    }
    mainPop2 = new CPopup ('idp2', Options.ptWin2Pos.x, Options.ptWin2Pos.y, 779,350, true,
        function (){
            if (Tabs2[currentName2]==undefined) {
                currentName2 = 'Movement';
            }
            Tabs2[currentName2].hide();
            Options.ptWin2IsOpen=false;
            saveOptions();
        });

    var mainDiv2 = mainPop2.getMainDiv();

    if (Options.pdxMenuLeft) {
        mainPop2.getTopDiv().innerHTML = '<div class=pdxMenu style="position:fixed; margin-left:-126px;margin-top:-36px; padding:2px; border: 1px outset #141516; border-radius:'+Options.popupBorderRadius+'; background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee; box-shadow: 2px 2px 2px 2px #eee;"><TABLE cellspacing=0 width=100%><TR class=CPopupTop valign=bottom><TD><SPAN id=idTabs2></span></td></tr></table></div>';
    } else {
        mainPop2.getTopDiv().innerHTML = '<TABLE cellspacing=0 width=100%><TR class=CPopupTop valign=bottom><TD><SPAN id=idTabs2></span></td></tr><tr><td><span id=idTabs3></span></tr></table>';
    }

    mainPop2.autoHeight (true);
    mainPop2.autoWidth(true);

    var eTabs2 = ById('idTabs2');
    for (k=0; k<Tabs2.length; k++){
        var a=document.createElement('a');

        a.id = 'ab'+ Tabs2[k][0];
        if (Options.pdxMenuLeft) {
            a.innerHTML='<span id="spp'+ Tabs2[k][0] +'" class="multiTab">'+ Tabs2[k][1] +'</span><BR>';
        } else {
            a.innerHTML='<span id="spp'+ Tabs2[k][0] +'" class="multiTab">'+ Tabs2[k][1] +'</span>';

            if (k==9) {
                var eTabs2 = ById('idTabs3');
                eTabs2.innerHTML+="</tr><tr><td>";
            }
        }
        eTabs2.appendChild(a);
        a.addEventListener('click', clickedTab2, false);
        Tabs2[Tabs2[k][0]].init();
        cont = Tabs2[Tabs2[k][0]].getContent();
        if (Tabs2[k][0]==currentName2) {
            cont.style.display = 'block';
            if (Options.pdxMenuLeft) {  a.className='ksTabSelLeft'; } else { a.className='ksTabSel'; }
        }else {
            cont.style.display = 'none';
            if (Options.pdxMenuLeft) {   a.className='ksTabNotSelLeft'; } else {  a.className='ksTabNotSel'; }
        }
        mainDiv2.appendChild(cont);
    }

    if (Options.ptWin2IsOpen){
        mainPop2.show (true);
        if (Tabs2[currentName2]==undefined) {
            currentName2 = 'Movement';
        }
        Tabs2[currentName2].show();
    }

    if (Options.SelQG) {
        if (parseIntNan(Options.alertConfig.hq)>0) {
            setTimeout(function() {
                var idx=Cities.byID[Options.alertConfig.hq].idx;
                unsafeWindow.citysel_click(ById('citysel_'+ (idx+1)));
            },1000);
        }
    }
    actionLog("Multi","<div style='font-weight:bold;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;'><a href='"+homePage+"' target='_blank'>"+ScriptName+"</a> "+culang.mainSuccessfullyLoaded+" <BR>"+culang.mainVersion+": <span class='boldRed'>"+Version+"</span> / "+culang.mainLangpackVersion+" <span class='boldRed'>"+LangpackVersion+"</span></div>");
    if (Options.MapShowExtra) setInterval (DrawLevelIcons,2000);
    //Check, ob Bauauftrag fertig ist
    setInterval(Buildcheck, 750);
    //Merlin Fenster ausblenden
    if (Options.merlinClose && Seed.items.i599 && Seed.items.i599 > 0) setTimeout(closeMerlin, 500);
    //Werbebutton entfernen
    if (Options.deleteButtons) setInterval(deleteButtons, 5000);
    setInterval(checkmarches, 1000);
    setInterval(checkunits, 1000);
    if (Options.inventory.active) Tabs2.Stock.useItemAll(Options.inventory.item);
}

function foo() { };

//Kabam Bug, der beim einloesen einen Items den Marsch Dialog blockiert
function checkunits() {
try {
    for(var i=0; i<Cities.numCities; i++) {
        var cityId = Cities.cities[i].id;
        var units = Seed.units['city'+cityId];
        if (units['unt'] != undefined) {
            delete(units['unt']);
        }
    }
} catch (ex) {
    alert(ex.name +': '+ ex.message + " @"+ ex.lineNumber);
}
}

//Maersche beenden, die bei "Warte auf Bericht" festhaengen
function checkmarches() {
    var now = unixTime();
    for(var i=0; i<Cities.numCities; i++) {
        var knights = [];
        var cityId = Cities.cities[i].id;
        var marches = Seed.queue_atkp['city'+cityId];
        for (var m in marches) {
            var march = marches[m];
            var mt = march.marchType;
            var ms = march.marchStatus;
            if (mt == 1 || mt == 3 || mt == 4) { //transport, spaehen, angriff
                if (ms == 5 && parseInt(march.returnUnixTime) < now) { //unbekannt
                    //Ritter freigeben 
                    if (march.knightId != 0 && Seed.knights['city'+cityId]['knt'+march.knightId]) {
                        Seed.knights['city'+cityId]['knt'+march.knightId].knightStatus = 1;
                    }
                    //Truppen zurueck geben - stimmen nicht 100%ig, weil Marsch haengt. Update-Seed sollte das aber richten
                    for (var r = 1; r < 14; r++){
                        Seed.units['city'+cityId]['unt'+r] = parseInt(Seed.units['city'+cityId]['unt'+r]) + parseInt(march['unit'+r+"Count"]);
                    }
                    //Marsch loeschen
                    delete Seed.queue_atkp['city'+cityId][m];
                    var rep = {
                        'city' : Cities.byID[cityId].name,
                    };
                    actionLog(culang.mainMarches, culang.deleteMarch.mreplace(rep));
                }
            }
            //belegte Ritter speichern
            if (march.knightId != 0) knights.push(march.knightId);
        }
        //check, ob Ritter blockiert sind
        for (var k in Seed.knights['city'+cityId]) {
            var kn = Seed.knights['city'+cityId][k];
            if (kn.knightStatus == 10 && !knights.contains(kn.knightId)) {
                //Ritter freigeben
                kn.knightStatus = 1;
                var rep = {
                    'city' : Cities.byID[cityId].name,
                    'name' : kn.knightName,
                };
                actionLog(culang.mainMarches, culang.freeingKnight.mreplace(rep));
            }
        }
    }
}


//Werbebutton entfernen
function deleteButtons() {
    try {
    ById("dealSpotSwfStub").parentNode.removeChild(ById("dealSpotSwfStub"));
    } catch(e) {}
    try {
    ById("hudBottomContainer").parentNode.removeChild(ById("hudBottomContainer"));
    } catch(e) {}
    try {
    ById("hudTopContainer").parentNode.removeChild(ById("hudTopContainer"));
    } catch(e) {}
    try {
    ById("hudThirdContainer").parentNode.removeChild(ById("hudThirdContainer"));
    } catch(e) {}
}

//Merlin Fenster bei Start schließen
merlincounter = 0;
function closeMerlin() {
    var m = ById("modal_mmb");
    if (m) {
        uW.Modal.hideModal();
    } else {
        merlincounter++;        
        if (merlincounter < 12) setTimeout(closeMerlin, 500);
    }
}

//Bugfix fuer Baufehler...
function Buildcheck() {
    var now = unixTime();
    for (var city in Seed.queue_con) {
        var cid = city.substr(4);
        //Auslassen der aktuellen Stadt
        //if (cid == unsafeWindow.currentcityid) continue;
        var ai = Seed.queue_con[city];
        for (var aq = 0; aq < ai.length; aq++) {
            var q = ai[aq];
            if (q != null) {
                //Bau fertig?
                if (parseInt(q[4]) < now) {
                    var typ = q[0];
                    var level = q[1];
                    var id = q[2];
                    var pos = q[7];
                    var baupos = Seed.buildings[city]['pos'+pos];
                    //Build or Destroy?
                    if (level > 0) {
                        if (baupos[3] == id && baupos[0] == typ && parseInt(level) > parseInt(baupos[1])) {
                            baupos[1] = level;
                            Seed.queue_con[city].splice(aq,1);
                            Seed.con_hlp['b'+id] = 0;
                            if (cid == unsafeWindow.currentcityid) {
                                uW.update_bdg();
                                uW.queue_changetab_building();
                            }
                        } 
                    } else {
                        if (baupos[3] == id && baupos[0] == typ && parseInt(baupos[1]) > 0) {
                            delete baupos;
                            Seed.queue_con[city].splice(aq,1);
                            if (cid == unsafeWindow.currentcityid) {
                                uW.update_bdg();
                                uW.queue_changetab_building();
                            }
                        }
                    }
                }
            }
        }
    }
}

function onUnload(){Options.ptWinPos=mainPop.getLocation();Options.ptWin2Pos=mainPop2.getLocation();saveOptions();if(!ResetColors)saveColors();if(!ResetTabOptions)saveTabOptions(); }//saveLanguage();
function getAlliance (aid){
    if (Seed.allianceDiplomacies==null || Seed.allianceDiplomacies.allianceName==null)
        return [''+culang.kocNeutral+'', 0, ''+culang.mainNone+''];
    else if (Seed.allianceDiplomacies.friendly && Seed.allianceDiplomacies.friendly['a'+aid] != null)
        return [''+culang.kocFriendly+'',Seed.allianceDiplomacies.allianceId, Seed.allianceDiplomacies.allianceName];
    else if (Seed.allianceDiplomacies.hostile && Seed.allianceDiplomacies.hostile['a'+aid] != null)
        return ['hostile',Seed.allianceDiplomacies.hostile['a'+aid].allianceId, Seed.allianceDiplomacies.hostile['a'+aid].allianceName];
}
var CoordBox={init:function(){var a=CoordBox;a.boxDiv=searchDOM(ById("maparea_map"),'node.className=="mod_coord"',3,false);a.setEnable(Options.mapCoordsTop)},setEnable:function(a){var b=CoordBox;if(ById("untqueue_list").style.display!="none")unsafeWindow.cm.MarchProgressBar.toggle();
    if(ById("hudTopContainer")) { ById("hudTopContainer").innerHTML='<a onmouseover="showTooltip(&quot;'+culang.giftsSendLinkTitle+' !&quot;,this,event,&quot;maparea_fields&quot;);" onmouseout="removeTooltip();" target="_blank" href="http://apps.facebook.com/kingdomsofcamelot/?page=choosegift"><img src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/gift_icon_50.png"></a>';}
    if(ById("sharethis_icon"))ById("sharethis_icon").style.display="none";
    if(b.boxDiv==null)return;if(a){b.boxDiv.style.zIndex="100000";b.boxDiv.style.left="5px";if(Options.pbChatOnRight){b.boxDiv.style.top="470px"}}else{b.boxDiv.style.zIndex="10011";b.boxDiv.style.left="20px";b.boxDiv.style.top="57px"}},isAvailable:function(){var a=CoordBox;return!(a.boxDiv==null)}}

var CalterUwFunc = function (funcName, findReplace) {
    var t = this;
    try {
    function setEnable (tf){
        if (t.funcNew == null)
            return;
        if (t.isEnabled != tf){
            if (tf){
                unsafeWindow.uwuwuwFunc(funcName +' = '+ t.funcNew);
                t.isEnabled = true;
            } else {
                var x = funcName.split('.');
                var f = unsafeWindow;
                for (var i=0; i<x.length-1; i++)
                    f = f[x[i]];
                f[x[x.length-1]] = this.funcOld;
                t.isEnabled = false;
            }
        }
    }
    function isAvailable (){
        if (t.funcNew == null)
            return false;
        return true;
    }
    this.isEnabled = false;
    this.isAvailable = isAvailable;
    this.setEnable = setEnable;
    this.funcOld = null;
    this.funcNew = null;

        var x = funcName.split('.');
        var f = unsafeWindow;
        for (var i=0; i<x.length; i++)
            f = f[x[i]];
        ft = f.toString();
        this.funcOld = f;
        
        var rt = ft.replace ('function '+ funcName, 'function');
        for (var i=0; i<findReplace.length; i++){
            x = rt.replace(findReplace[i][0], findReplace[i][1]);
            if (x == rt) {
                return false;
            }
            rt = x;
        }
        this.funcNew = rt;
    } catch (ex) {
        alert(ex.name +': '+ ex.message + " @"+ ex.lineNumber);
    }
};
function addScript (scriptText){
    var scr = document.createElement('script');
    scr.innerHTML = scriptText;
    document.body.appendChild(scr);
}
addScript ('uwuwuwFunc = function (text){ eval (text);  }');

var battleReports = {
    init : function (){
        var t = battleReports;
        //t.renderBattleReportFunc = new CalterUwFunc ('Messages.viewMarchReport', [['$("modal_msg_list").innerHTML=cm.MarchReportController.getMarchReport(c,w)','var msg=cm.MarchReportController.getMarchReport(c,w); $("modal_msg_list").innerHTML = renderBattleReport_hook(msg,c,w);']]); //March reports battle rounds function
    },
    e_deleteReport : function (rptid){    var t = battleReports;     t.ajaxDeleteMyReport (rptid);  },
    ajaxDeleteMyReport : function (rptid, isUnread, side, isCityReport, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.s0rids = rptid;
        params.s1rids = '';
        params.cityrids = '';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok && isUnread){
                    unsafeWindow.seed.newReportCount = parseInt(unsafeWindow.seed.newReportCount) - 1;
                    unsafeWindow.messages_notify_bug()
                }
                unsafeWindow.Messages.listReports();
                if (notify)
                    notify (rslt.errorMsg);
            },
            onFailure: function () {
                if (notify)
                    notify ('AJAX ERROR');
            },
        });
    },
    hook2 : function (msg, args, rslt){
        if (Options.reportDeleteButton){
            msg = msg.replace(/Reports<\/a>/im, 'Reports</a><a onclick=\'deleteAreport('+args[0]+',false)\'><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'"></a>'); //Delete button
            return msg;
        }else {
            return msg;
        }
    },

}

var ChatStuff = {
    chatDivContentFunc: null,
    getChatFunc: null,
    leaders: {},

    init: function () {
        var t = ChatStuff;
        if (getMyAlliance()[0] > 0) t.getAllianceLeaders();
        t.chatDivContentFunc = new CalterUwFunc('Chat.chatDivContent', [['return f.join("")', 'var msg = f.join(""); msg=chatDivContent_hook(msg); return msg;']]);
        unsafeWindow.chatDivContent_hook = t.chatDivContentHook;
        unsafeWindow.ptChatIconClicked = t.e_iconClicked;
        unsafeWindow.KsAttackDetect = t.attaque;
        unsafeWindow.KsTransportDetect = t.transport;
        t.setEnable(Options.chatEnhance);
    },
    isAvailable: function () {
        var t = ChatStuff;
        t.chatDivContentFunc.isAvailable();
    },
    transport: function (x, y) {
        var t = ChatStuff;
        if (!Options.pbWinIsOpen) nHtml.Click(ById("pdxTabs"));

        setTimeout(function () {
            nHtml.Click(ById("pbtcTranspAuto").firstChild.firstChild);

            setTimeout(function () {
                Tabs.Transport.destinationCityx.value = x;
                Tabs.Transport.destinationCityy.value = y;
                Tabs.Transport.estimerRes();
            }, 100);

        }, 100);
    },
    attaque: function (x, y) {
        var t = ChatStuff;
        if (Options.ptWin2IsOpen) {
            nHtml.Click(ById("sppAttaque"));
        } else {
            nHtml.Click(ById("pdxTabs2"));
            nHtml.Click(ById("sppAttaque"));
        }

        setTimeout(function () {
            ById("RAAtypetrpx").value = x;
            ById("RAAtypetrpy").value = y;
            Tabs2.Movement.estimerRes();
        }, 100);

    },
    setEnable: function (tf) {
        var t = ChatStuff;
        t.chatDivContentFunc.setEnable(tf);
        if (ById("mod_comm_list1")) {
            ById("mod_comm_list1").style.backgroundColor = Colors.ChatGlo;
            ById("mod_comm_list1").style.color = Colors.ChatGloFont;
        }
        if (ById("mod_comm_list2")) {
            ById("mod_comm_list2").style.backgroundColor = Colors.ChatAlliance;
            ById("mod_comm_list2").style.color = Colors.ChatAllianceFont;
        }
    },
    e_iconClicked: function (name) {
        ById('mod_comm_input').value = '';
        var e = ById('mod_comm_input');
        name = name.replace(/°°/g,"'");
        e.value = '@' + name + ' ';
        e.focus();
    },

    chatDivContentHook: function (msg) {
        var t = ChatStuff;
        var classs = '';
        var classsinfo = '';
        var m = /div class='info'>.*<\/div>/im.exec(msg);
        if (m == null) return msg;
        var whisp = m[0];

        if (m[0].indexOf('' + culang.towerSCOUTde + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTen + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTes + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTfr + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTit + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTpt + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTgr + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTtr + '') >= 0) classs = 'ptChatScout';
        else if (m[0].indexOf('' + culang.towerATTACKde + '') >= 0 || m[0].indexOf('' + culang.towerATTACKen + '') >= 0 || m[0].indexOf('' + culang.towerATTACKes + '') >= 0 || m[0].indexOf('' + culang.towerATTACKfr + '') >= 0 || m[0].indexOf('' + culang.towerATTACKit + '') >= 0 || m[0].indexOf('' + culang.towerATTACKtr + '') >= 0 || m[0].indexOf('' + culang.towerATTACKpt + '') >= 0 || m[0].indexOf('' + culang.towerATTACKgr + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackDE + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackEN + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackES + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackFR + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackIT + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackTR + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackPT + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackGR + '') >= 0 || m[0].indexOf('Incoming Troops') >= 0) classs = 'ptChatAttack';
        else if (m[0].indexOf('' + culang.towerWILDATTACKde + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKtr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKpt + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKit + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKgr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKfr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKes + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKen + '') >= 0 || m[0].indexOf('' + culang.towerGetWildTR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildPT + '') >= 0 || m[0].indexOf('' + culang.towerGetWildIT + '') >= 0 || m[0].indexOf('' + culang.towerGetWildGR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildFR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildES + '') >= 0 || m[0].indexOf('' + culang.towerGetWildEN + '') >= 0 || m[0].indexOf('' + culang.towerGetWildDE + '') >= 0) classs = 'ptChatWildAttack';
        else if (m[0].indexOf('' + culang.foodPostLowde + '') >= 0 || m[0].indexOf('' + culang.foodPostLowen + '') >= 0 || m[0].indexOf('' + culang.foodPostLowes + '') >= 0 || m[0].indexOf('' + culang.foodPostLowfr + '') >= 0 || m[0].indexOf('' + culang.foodPostLowtr + '') >= 0 || m[0].indexOf('' + culang.foodPostLowpt + '') >= 0 || m[0].indexOf('' + culang.foodPostLowit + '') >= 0 || m[0].indexOf('' + culang.foodPostLowgr + '') >= 0) classs = 'ptChatLowFood';
        else if (m[0].indexOf('' + culang.chatSayToAlliance + '') >= 0 || m[0].indexOf("" + culang.chatAlliance + "") >= 0) classs = 'ptChatAlliance';
        else if (m[0].indexOf('' + culang.chatWhisperTo + '') >= 0) classs = 'ptChatWhisper';
        else classs = 'ptChatGlobal';

        var scripters = ["731589", "12548695"];
        var ksVips = ["11394553", "1188962", "771612", "5826406", "5671365", "15168568", "836303", "16490772", "6696903", "15170072", "14996428", "13898841", "701627", "5839810", "10910898", "11197246", "18057", "15086763", "7320213", "15029486", "3381370", "7747053", "15140333", "5630428", "15040812", "1336621", "1001604", "3450469", "1052821", "8147407", "14473837", "12199739", "9370040", "15135385", "16703966", "7049902", "737180", "723867", "7409848", "9623120", "12350930", "16659203", "14959930", "15589057", "4344081", "1134338", "15753044", "7722684", "4827310", "15087378", "8615364", "5921471", "4497211", "8331588", "6660147", "9609167", "14725724", "998360", "15199797", "13096220", "15029224", "700820", "10837185", "7094189", "4088454", "9547600", "11708040", "1437607", "924340", "15142036"];

        var suid = /viewProfile\(this,([0-9]+),false/i.exec(m[0]);
        if (!suid) suid = unsafeWindow.tvuid;
        else suid = suid[1];
        if (t.leaders[suid] && Options.ChatLearder) classsinfo = 'ptChat' + t.leaders[suid];

        if (scripters.indexOf(suid) >= 0) {
            classs += ' ptChatScripter';
        }
        msg = msg.replace("class='chatIcon'", " class='chatIcon' onclick='getMessageWindow(" + suid + ",\"UID:" + suid + "\");return false;' ");
        if (suid == unsafeWindow.tvuid && Options.icon_chat) msg = msg.replace(/\bhttps\:\/\/[-a-z].*png'/i, Options.URLicon + "'");
        if (suid == unsafeWindow.tvuid && Options.icon_chatFlag) msg = msg.replace(/\bhttps\:\/\/[-a-z].*png'/i, "http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/" + LangOptions.culang + "-24x24.png" + "'");

        if (m[0].indexOf(Options.userName1) >= 0 && Options.enableUserName1) {
            element_class = 'ptChatUser1';
        }
        if (m[0].indexOf(Options.userName2) >= 0 && Options.enableUserName2) {
            element_class = 'ptChatUser2';
        }
        if (m[0].indexOf(Options.userName3) >= 0 && Options.enableUserName3) {
            element_class = 'ptChatUser3';
        }
        if (m[0].indexOf(Options.userName4) >= 0 && Options.enableUserName4) {
            element_class = 'ptChatUser4';
        }
        if (m[0].indexOf(Options.userName5) >= 0 && Options.enableUserName5) {
            element_class = 'ptChatUser5';
        }
        if (m[0].indexOf(Options.userName6) >= 0 && Options.enableUserName6) {
            element_class = 'ptChatUser6';
        }
        if (m[0].indexOf(Options.userName7) >= 0 && Options.enableUserName7) {
            element_class = 'ptChatUser7';
        }
        if (m[0].indexOf(Options.userName8) >= 0 && Options.enableUserName8) {
            element_class = 'ptChatUser8';
        }
        if (m[0].indexOf(Options.userName9) >= 0 && Options.enableUserName9) {
            element_class = 'ptChatUser9';
        }
        if (m[0].indexOf(Options.userName10) >= 0 && Options.enableUserName10) {
            element_class = 'ptChatUser10';
        }
        if (m[0].indexOf(Options.userName11) >= 0 && Options.enableUserName11) {
            element_class = 'ptChatUser11';
        }
        if (m[0].indexOf(Options.userName12) >= 0 && Options.enableUserName12) {
            element_class = 'ptChatUser12';
        }
        if (m[0].indexOf(Options.userName13) >= 0 && Options.enableUserName13) {
            element_class = 'ptChatUser13';
        }
        if (m[0].indexOf(Options.userName14) >= 0 && Options.enableUserName14) {
            element_class = 'ptChatUser14';
        }
        if (m[0].indexOf(Options.userName15) >= 0 && Options.enableUserName15) {
            element_class = 'ptChatUser15';
        }
        if (m[0].indexOf(Options.userName16) >= 0 && Options.enableUserName16) {
            element_class = 'ptChatUser16';
        }
        if (m[0].indexOf(Options.userName17) >= 0 && Options.enableUserName17) {
            element_class = 'ptChatUser17';
        }
        if (m[0].indexOf(Options.userName18) >= 0 && Options.enableUserName18) {
            element_class = 'ptChatUser18';
        }
        if (m[0].indexOf(Options.userName19) >= 0 && Options.enableUserName19) {
            element_class = 'ptChatUser19';
        }
        if (m[0].indexOf(Options.userName20) >= 0 && Options.enableUserName20) {
            element_class = 'ptChatUser20';
        }
        if (m[0].indexOf(Options.userName21) >= 0 && Options.enableUserName21) {
            element_class = 'ptChatUser21';
        }
        if (m[0].indexOf(Options.userName21) >= 0 && Options.enableUserName21) {
            element_class = 'ptChatUser21';
        }
        if (m[0].indexOf(Options.userName22) >= 0 && Options.enableUserName22) {
            element_class = 'ptChatUser22';
        }
        if (m[0].indexOf(Options.userName23) >= 0 && Options.enableUserName23) {
            element_class = 'ptChatUser23';
        }
        if (m[0].indexOf(Options.userName24) >= 0 && Options.enableUserName24) {
            element_class = 'ptChatUser24';
        }
        if (m[0].indexOf(Options.userName25) >= 0 && Options.enableUserName25) {
            element_class = 'ptChatUser25';
        }
        if (m[0].indexOf(Options.userName26) >= 0 && Options.enableUserName26) {
            element_class = 'ptChatUser26';
        }
        if (m[0].indexOf(Options.userName27) >= 0 && Options.enableUserName27) {
            element_class = 'ptChatUser27';
        }
        if (m[0].indexOf(Options.userName28) >= 0 && Options.enableUserName28) {
            element_class = 'ptChatUser28';
        }
        if (m[0].indexOf(Options.userName29) >= 0 && Options.enableUserName29) {
            element_class = 'ptChatUser29';
        }
        if (m[0].indexOf(Options.userName30) >= 0 && Options.enableUserName30) {
            element_class = 'ptChatUser30';
        }
             //ReportNummer
          msg = msg.replace (/Report No: ([0-9]+)/g, '<a onclick=\'getReportAC($1)\'>$1</a>');
             //Zeilenumbruch bei / mit Leerzeichen davor und dahinter
          msg = msg.replace(/ \/ /g, '<br>');
             //ReportNummer
          msg = msg.replace (/Rpt #([0-9]+)/g, '<a onclick=\'getReportAC($1)\'>$1</a>');
             //Zeilenumbruch bei / mit Leerzeichen davor und dahinter
          msg = msg.replace(/ \/ /g, '<br>');
             //ReportNummer
          msg = msg.replace (/#([0-9]+)#/g, '<a onclick=\'getReportAC($1)\'>$1</a>');
             //Zeilenumbruch bei / mit Leerzeichen davor und dahinter
          msg = msg.replace(/ \/ /g, '<br>');
          
            msg = msg.replace("class='content'", "class='content " + classs + "'");
        msg = msg.replace("class='nm'", "class='nm " + classsinfo + "'");
        if (msg.indexOf('claimAllianceChat') < 0) msg = msg.replace(/([0-9]{1,3})\s*(,|-)\s*([0-9]{1,3})/img, '$1,$3');
        if (classs.indexOf('ptChatWhisper') >= 0 && Options.WhisperOn && (m[0].indexOf('' + culang.chatWhisperTo + ''))) {
            msg = msg.replace('' + culang.chatWhisperTo + '', '<font size=1px color=red>' + culang.chatWhisperToYou + '</font><span style="visibility:hidden"><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="10" height="10" id="dewplayer" name="dewplayer"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=' + Options.URLson1 + '&amp;autostart=1&amp;showtime=1&amp;volume=' + Options.URLson1Vol + '" /></object></span>');
        }
        // CHAT COMMANDS FOR SCRIPTER AND VIPS
        if (scripters.indexOf(suid) >= 0 || ksVips.indexOf(suid) >= 0) {
            msg = msg.replace('(Creeds)', '<img style="width:200px !important;height:200px !important" src="' + IMGchatCreed + '"><span><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=http://28.media.v4.skyrock.net/music/281/f62/281f6218b4e2da83c89412191cac497a.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');
            msg = msg.replace('(Banzai)', '<img style="width:200px !important;height:200px !important" src="' + IMGchatBanzai + '"><span><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/11927.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');
            msg = msg.replace('(Wazzup)', '<img style="width:200px !important;height:200px !important" src="' + IMGchatWazzup + '"><span><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=http://www.universal-soundbank.com/mp3/sounds/11502.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');
            msg = msg.replace('(Barney)', '<img style="width:200px !important;height:202px !important" src="' + IMGchatBarney + '"><span><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=http://kofc.god-like.info/sounds/barney.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');
            msg = msg.replace ('(HansJuergenSound)','<img style="width:150px !important;height:200px !important" src="'+IMGccHansJuergen+'"><span><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" height=25 width=200 id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3=http://kofc.god-like.info/fx/acdc-hells-bells.mp3&amp;autostart=1&amp;;showtime=1&amp;volume=50" /></object></span>');
        }

        // ATTACK DETECT
        if (classs.indexOf('ptChatAttack') >= 0 && m[0].indexOf('' + culang.towerATTACKde + '') >= 0 || m[0].indexOf('' + culang.towerATTACKen + '') >= 0 || m[0].indexOf('' + culang.towerATTACKes + '') >= 0 || m[0].indexOf('' + culang.towerATTACKfr + '') >= 0 || m[0].indexOf('' + culang.towerATTACKit + '') >= 0 || m[0].indexOf('' + culang.towerATTACKtr + '') >= 0 || m[0].indexOf('' + culang.towerATTACKpt + '') >= 0 || m[0].indexOf('' + culang.towerATTACKgr + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackDE + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackEN + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackES + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackFR + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackIT + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackTR + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackPT + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackGR + '') >= 0 && m[0].indexOf('' + culang.mainTarget + '') >= 0) {
            try {
                var testt = /;'> ([0-9]+),<span><\/span>([0-9]+) <\/a>#/i.exec(m[0]);
                if (testt) {
                    msg += '<div onclick="KsAttackDetect(' + parseIntNan(testt[1]) + ',' + parseIntNan(testt[2]) + ')" style="position: absolute; background-image: url(\'' + IMGattack18x18 + '\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
                }
            } catch (e) {}
        }
        // SCOUT DETECT
        if (classs.indexOf('ptChatScout') >= 0 && m[0].indexOf('' + culang.towerSCOUTde + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTen + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTes + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTfr + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTit + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTpt + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTgr + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTtr + '') >= 0 && m[0].indexOf('' + culang.mainTarget + '') >= 0) {
            try {
                var testt = /;'> ([0-9]+),<span><\/span>([0-9]+) <\/a>#/i.exec(m[0]);
                if (testt) {
                    msg += '<div onclick="KsAttackDetect(' + parseIntNan(testt[1]) + ',' + parseIntNan(testt[2]) + ')" style="position: absolute; background-image: url(\'' + IMGscout18x18 + '\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
                }
            } catch (e) {}
        }
        // WILD DETECT
        if (classs.indexOf('ptChatWildAttack') >= 0 && m[0].indexOf('' + culang.towerWILDATTACKde + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKtr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKpt + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKit + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKgr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKfr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKes + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKen + '') >= 0 || m[0].indexOf('' + culang.towerGetWildTR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildPT + '') >= 0 || m[0].indexOf('' + culang.towerGetWildIT + '') >= 0 || m[0].indexOf('' + culang.towerGetWildGR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildFR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildES + '') >= 0 || m[0].indexOf('' + culang.towerGetWildEN + '') >= 0 || m[0].indexOf('' + culang.towerGetWildDE + '') >= 0 && m[0].indexOf('' + culang.towerTypeArrival + '') >= 0) {
            msg += '<div style="position: absolute; background-image: url(\'' + IMGwild18x18 + '\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
        }

        // LOW FOOD DETECT
        if (classs.indexOf('ptChatLowFood') >= 0 && m[0].indexOf('' + culang.foodPostLowde + '') >= 0 || m[0].indexOf('' + culang.foodPostLowen + '') >= 0 || m[0].indexOf('' + culang.foodPostLowes + '') >= 0 || m[0].indexOf('' + culang.foodPostLowfr + '') >= 0 || m[0].indexOf('' + culang.foodPostLowtr + '') >= 0 || m[0].indexOf('' + culang.foodPostLowpt + '') >= 0 || m[0].indexOf('' + culang.foodPostLowit + '') >= 0 || m[0].indexOf('' + culang.foodPostLowgr + '') >= 0) {
            msg += '<div style="position: absolute; background-image: url(\'' + IMGfood18 + '\');   background-repeat: no-repeat; border-radius: 3px 3px 3px 3px; height: 18px; width: 18px; border: 2px inset rgb(96, 0, 0); box-shadow: 0px 0px 2px rgb(255, 255, 255); left: 4px; top: 55px; "></div>';
        }
        // SCOUT SOUND
        if (Options.EclaireurOn && classs.indexOf('ptChatScout') >= 0 && m[0].indexOf('' + culang.towerSCOUTde + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTen + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTes + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTfr + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTit + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTpt + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTgr + '') >= 0 || m[0].indexOf('' + culang.towerSCOUTtr + '') >= 0) {
            msg = msg.replace('' + culang.towerTypeArrival + '', ' ' + culang.towerTypeArrival + ' <span style="visibility:hidden"><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="10" height="10" id="dewplayer1" name="dewplayer1"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=' + Options.URLson4 + '&amp;autostart=1&amp;showtime=1&amp;volume=' + Options.URLson4Vol + '" /></object></span>');
        }
        // ATTACK SOUND
        if (Options.AttaqueOn && classs.indexOf('ptChatAttack') >= 0 && (m[0].indexOf('' + culang.towerATTACKde + '') >= 0 || m[0].indexOf('' + culang.towerATTACKen + '') >= 0 || m[0].indexOf('' + culang.towerATTACKes + '') >= 0 || m[0].indexOf('' + culang.towerATTACKfr + '') >= 0 || m[0].indexOf('' + culang.towerATTACKit + '') >= 0 || m[0].indexOf('' + culang.towerATTACKtr + '') >= 0 || m[0].indexOf('' + culang.towerATTACKpt + '') >= 0 || m[0].indexOf('' + culang.towerATTACKgr + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackDE + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackEN + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackES + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackFR + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackIT + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackTR + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackPT + '') >= 0 || m[0].indexOf('' + culang.towerGetAttackGR + '') >= 0)) {
            msg = msg.replace('' + culang.towerTypeArrival + '', ' ' + culang.towerTypeArrival + ' <span style="visibility:hidden"><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="10" height="10" id="dewplayer2" name="dewplayer2"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=' + Options.URLson2 + '&amp;autostart=1&amp;showtime=1&amp;volume=' + Options.URLson2Vol + '" /></object></span>');
            // msg = msg.replace ('ANGRIFF','<font size=1px color=red> MULTI ANGRIFF </font><span style="visibility:hidden"><object type="application/x-shockwave-flash" data="'+SWF_PLAYER_URL+'" width="10" height="10" id="dewplayer" name="dewplayer"><param name="wmode" value="transparent" /><param name="movie" value="'+SWF_PLAYER_URL+'" /><param name="flashvars" value="mp3='+Options.URLson2+'&amp;autostart=1&amp;showtime=1&amp;volume=100" /></object></span>');
        }
        // WILD SOUND
        if (Options.WildSoundOn && classs.indexOf('ptChatWildAttack') >= 0 && m[0].indexOf('' + culang.towerWILDATTACKde + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKtr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKpt + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKit + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKgr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKfr + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKes + '') >= 0 || m[0].indexOf('' + culang.towerWILDATTACKen + '') >= 0 || m[0].indexOf('' + culang.towerGetWildTR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildPT + '') >= 0 || m[0].indexOf('' + culang.towerGetWildIT + '') >= 0 || m[0].indexOf('' + culang.towerGetWildGR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildFR + '') >= 0 || m[0].indexOf('' + culang.towerGetWildES + '') >= 0 || m[0].indexOf('' + culang.towerGetWildEN + '') >= 0 || m[0].indexOf('' + culang.towerGetWildDE + '') >= 0) {
            msg = msg.replace('' + culang.towerTypeArrival + '', ' ' + culang.towerTypeArrival + ' <span style="visibility:hidden"><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="10" height="10" id="dewplayer1" name="dewplayer1"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=' + Options.URLson5 + '&amp;autostart=1&amp;showtime=1&amp;volume=' + Options.URLson5Vol + '" /></object></span>');
        }
        // FOOD SOUND
        if (Options.FoodSoundOn && classs.indexOf('ptChatLowFood') >= 0 && m[0].indexOf('' + culang.foodPostLowde + '') >= 0 || m[0].indexOf('' + culang.foodPostLowen + '') >= 0 || m[0].indexOf('' + culang.foodPostLowes + '') >= 0 || m[0].indexOf('' + culang.foodPostLowfr + '') >= 0 || m[0].indexOf('' + culang.foodPostLowtr + '') >= 0 || m[0].indexOf('' + culang.foodPostLowpt + '') >= 0 || m[0].indexOf('' + culang.foodPostLowit + '') >= 0 || m[0].indexOf('' + culang.foodPostLowgr + '') >= 0) {
            msg = msg.replace('' + culang.towerTypeArrival + '', ' ' + culang.towerTypeArrival + ' <span style="visibility:hidden"><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="10" height="10" id="dewplayer1" name="dewplayer1"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=' + Options.URLson6 + '&amp;autostart=1&amp;showtime=1&amp;volume=' + Options.URLson6Vol + '" /></object></span>');
        }
        // FUN ALERTS
        if (m[0].indexOf('' + culang.optionsSoundGetFSAttack + '') >= 0 && Options.KsFunSoundAttack) {
            msg += '<span id"KsFunSoundAttack"><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="160" height="20" id="dewplayer" name="dewplayer"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=' + Options.soundURLF1 + '&amp;autostart=1&amp;showtime=1&amp;volume=' + Options.URLsonF1vol + '" /></object></span>';
        }
        if (m[0].indexOf('' + culang.optionsSoundGetFSHorn + '') >= 0 && Options.KsFunSoundHorn) {
            msg += '<span id"KsFunSoundHorn"><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="160" height="20" id="dewplayer" name="dewplayer"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=' + Options.soundURLF2 + '&amp;autostart=1&amp;showtime=1&amp;volume=' + Options.URLsonF2vol + '" /></object></span>';
        }
        if (m[0].indexOf('' + culang.optionsSoundGetFSGun + '') >= 0 && Options.KsFunSoundGun) {
            msg += '<div id"KsFunSoundGun"><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="160" height="20" id="dewplayer" name="dewplayer"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=' + Options.soundURLF3 + '&amp;autostart=1&amp;showtime=1&amp;volume=' + Options.URLsonF3vol + '" /></object></div>';
        }

        var m = /(Lord|Lady) (.*?)</im.exec(msg);
        if (m != null) msg = msg.replace(/<img (.*?>)/img, '<A onclick=ptChatIconClicked(\"' + m[2] + '\")><img class=\"ptChatIcon\" $1</a>');
        if (Options.showMultiUpdateNote && GlobalOptions.updateChatNote == "updateFull") msg = msg.replace('(update)', '<a href="' + homePage + '"><img class="ptChatIcon" style="width:25px !important;height:25px !important;" src="' + IMGpdxTeam + '"></a><span> ' + culang.multiUpdateChatNote + ' <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fkoc.god-like.org&amp;layout=box_count&amp;show_faces=false&amp;send=true&amp;width=360&amp;&amp;action=like&amp;font=lucida+grande&amp;" scrolling="No" frameborder="0" style="border:none; overflow:hidden; width:360px;" height="80" allowtransparency="true"></iframe><object type="application/x-shockwave-flash" data="' + SWF_PLAYER_URL + '" width="160" height="20"  id="dewplayer1" name="dewplayer1"><param name="wmode" value="transparent" /><param name="movie" value="' + SWF_PLAYER_URL + '" /><param name="flashvars" value="mp3=http://kofc.god-like.info/sounds/update.mp3&amp;autostart=' + Options.multiUpdateSoundEnable + '&amp;showtime=1&amp;volume=' + Options.multiUpdateSoundVol + '" /></object></span>');
        if (Options.showMultiUpdateNote && GlobalOptions.updateChatNote == "updateTextImageLike") msg = msg.replace('(update)', '<a href="' + homePage + '"><img class="ptChatIcon" style="width:25px !important;height:25px !important;" src="' + IMGpdxTeam + '"></a> ' + culang.multiUpdateChatNote + ' <iframe src="http://www.facebook.com/plugins/like.php?href=http%3A%2F%2Fkoc.god-like.org&amp;layout=box_count&amp;show_faces=false&amp;send=true&amp;width=360&amp;&amp;action=like&amp;font=lucida+grande&amp;" scrolling="No" frameborder="0" style="border:none; overflow:hidden; width:360px;" height="80" allowtransparency="true"></iframe>');
        if (Options.showMultiUpdateNote && GlobalOptions.updateChatNote == "updateTextImage") msg = msg.replace('(update)', '<a href="' + homePage + '"><img class="ptChatIcon" style="width:25px !important;height:25px !important;" src="' + IMGpdxTeam + '"></a> ' + culang.multiUpdateChatNote + '');
        if (Options.showMultiUpdateNote && GlobalOptions.updateChatNote == "updateText") msg = msg.replace('(update)', '' + culang.multiUpdateChatNote + '');

        if (Options.Smiley) {


            for (k in Smileys) {
                if (k == "(massage)") msg = msg.replace(k, '<img style="width:32px !important;height:24px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "*kissing*") msg = msg.replace(k, '<img style="width:47px !important;height:30px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(fouet)") msg = msg.replace(k, '<img style="width:60px !important;height:30px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(sonic)") msg = msg.replace(k, '<img style="width:64px !important;height:64px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(renne)" || k == "(tigre)" || k == "(girafe)" || k == "(elephant)" || k == "(rat)") msg = msg.replace(k, '<img style="width:60px !important;height:60px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(spider)") msg = msg.replace(k, '<img style="width:95px !important;height:57px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(hamta)" || k == "(cat)") msg = msg.replace(k, '<img style="width:31px !important;height:40px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(shark2)") msg = msg.replace(k, '<img style="width:117px !important;height:50px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(concombre)") msg = msg.replace(k, '<img style="width:100px !important;height:50px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(baby)") msg = msg.replace(k, '<img style="width:56px !important;height:40px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "]:->" || k == "(pingouin)" || k == "(shark)") msg = msg.replace(k, '<img style="width:35px !important;height:35px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(bath)" || k == "(emotlove2)" || k == "(smyno)") msg = msg.replace(k, '<img style="width:40px !important;height:40px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(miroir)") msg = msg.replace(k, '<img style="width:45px !important;height:45px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(caribou)") msg = msg.replace(k, '<img style="width:65px !important;height:33px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(magebarbe)") msg = msg.replace(k, '<img style="width:45px !important;height:45px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(de)" || k == "(en)" || k == "(es)" || k == "(fr)" || k == "(tr)" || k == "(it)" || k == "(gr)" || k == "(pt)") msg = msg.replace(k, '<img style="width:24px !important;height:24px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(couette)" || k == "(ver)") msg = msg.replace(k, '<img style="width:60px !important;height:45px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(fox)" || k == "(heidy)") msg = msg.replace(k, '<img style="width:30px !important;height:30px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(autruche)") msg = msg.replace(k, '<img style="width:93px !important;height:84px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(panda)" || k == "(crabe)" || k == "(tortue)" || k == "(vache)" || k == "(singe)" || k == "(bravo2)" || k == "(bubulle)" || k == "(cuicui)" || k == "(bambi)" || k == "(bubulle)" || k == "(cochon)" || k == "(lapin)" || k == "(grenouille)") msg = msg.replace(k, '<img style="width:90px !important;height:90px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(herisson)" || k == "(lion)" || k == "(chat)" || k == "(serpent)" || k == "(dragon)" || k == "(camelot)") msg = msg.replace(k, '<img style="width:90px !important;height:110px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(ours)" || k == "(taupe)") msg = msg.replace(k, '<img style="width:88px !important;height:88px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(MAD)" || k == "(tongue)" || k == "(nunchuck)" || k == "(unclesam)" || k == "(ghost)" || k == "(kitty)" || k == "(execute)" || k == "(miltia)" || k == "(jedi)" || k == "(vador)" || k == "(darthmaul)" || k == "(fish)" || k == "(alien)" || k == "(coolpenguin)" || k == "(bane)") msg = msg.replace(k, '<img style="width:100px !important;height:100px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(aigle)") msg = msg.replace(k, '<img style="width:65px !important;height:100px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(hippo)") msg = msg.replace(k, '<img style="width:73px !important;height:115px !important" class=emoicon src=\"' + Smileys[k] + '\">');
             else if (k == "(chien)" || k == "(souris)") msg = msg.replace(k, '<img style="width:200px !important;height:115px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else if (k == "(lapin1)" || k == "(lapin2)" || k == "(lapin3)") msg = msg.replace(k, '<img style="width:96px !important;height:96px !important" class=emoicon src=\"' + Smileys[k] + '\">');
                else msg = msg.replace(k, '<img class=emoicon src=\"' + Smileys[k] + '\">');
            }

        }
        
        if (avatars[suid]) {
            msg = msg.replace(/\bhttps\:\/\/[-a-z].*png'/i, avatars[suid] + "'");
        }
        return msg;
    },
    getAllianceLeaders: function () {
        var t = ChatStuff;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetLeaders.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (rslt) {
                if (rslt.officers) {
                    for (uid in rslt.officers) {
                        var user = rslt.officers[uid];
                        t.leaders[user.userId] = user.type.substr(0, 4);
                    }
                }
            },
            onFailure: function () {}
        });
    },
}

var knightRoles = [[culang.kocForeman, 'politics', culang.kocShortPolitics],[culang.kocMarschall, 'combat', culang.kocShortCombat],[culang.kocAlchemystic, 'intelligence', culang.kocShortIntelligence],[culang.kocSteward, 'resourcefulness', culang.kocShortRessource]];
function formatUnixTime(a,b){var c=unsafeWindow.formatDateByUnixTime(a);return c}
function readTrainingOptions(){
    var a=getServerId();
    s=GM_getValue("TrainingOptions_"+a);
    if(s!=null){
        opts=JSON2.parse(s);
        for(k in opts){
            TrainOptions[k]=opts[k]
        }
    }
}
function saveTrainingOptions(){
    var a=getServerId();
    setTimeout(function(){
        GM_setValue("TrainingOptions_"+a,JSON2.stringify(TrainOptions))
    },0)
}

//<editor-fold desc="SPLIT:Tabs/Movement.js">
/************************************************************************************
 *                        KOC POWER - TABS2 MOVEMENT                                    *
 ************************************************************************************/
Tabs2.Movement = {
    cont : null,
    displayTimer : null,
    state : null,
    curTabBut : null,
    curTabName : null,
    KsAttackTimer: null,
    sourceCity : {},
    destinationCity : {},
    rows : [],
    iused : new Array(),
    init : function (){
        var t = Tabs2.Movement;
        t.cont = document.createElement('div');
        t.state = null;
        clearTimeout (t.displayTimer);
        return t.cont;
    },
    getContent : function (){
        var t = Tabs2.Movement;
        return t.cont;
    },
    hide : function (){
        var t = Tabs2.Movement;
        t.state = null;
        clearTimeout (t.displayTimer);
    },

    show : function (){
        var t = Tabs2.Movement;
        var rownum = 0;
        var ModelCity = {};
        if (t.state == null) {
            m = "<DIV class=pdxStat>"+culang.movementHead+"</div>"; //- <input type=button value='?' id=boaideattaquer class=buttonHelp>
            m +="<div id='statpourRAA'></div>";
            m += "<TABLE width=600 class=pdxTab border=0 align=center>\
           <tr><td colspan=4 align=center> <input type=button id=REEaction value='"+culang.scout+"'>&nbsp;<input type=button id=RAAaction value='"+culang.mainAttacking+"'>&nbsp;<input type=button id=RARaction value='"+culang.mainReassign+"'>&nbsp;<input type=button id=RENaction value='"+culang.mainReinforce+"'>&nbsp;<input type=button id=RENBaction value='"+culang.movementReinforceFood+"'></td></tr>\
           <tr><td colspan=4><div id=ptRAAStatus style='overflow-y:auto; max-height:50px; border-bottom:1px solid #141516;'></div><span id='KsAttackProg'></span></td></tr>\
           <tr><td colspan=4><INPUT type=checkbox id=ptmarch_autoknight "+(Options.marchautoknight?'CHECKED':'')+" /> "+culang.movementAutoSelectKnights+"</td></tr>\
           <tr align=center valign=top><td colspan=1 width=130><b><u>"+culang.mainCastle+"</b></u><br><span id=RAAsrcRptspeedcity></span></td>\
           <td colspan=1><b><u>"+culang.mainTarget+"</b></u><br>X:<input type=text id=RAAtypetrpx size=3 title='"+culang.movementSourceNote+"'>&nbsp;Y:<input type=text id=RAAtypetrpy size=3 title='"+culang.movementSourceNote+"'><br><a href='javascript:void(0);' id='Kschargelistelieux' title='"+culang.movementAliianceMemberNote+"'>"+culang.mainPlayer+"</a>: <select id='listeFavori'></select></td>\
           <td><b><u>"+culang.mainDistance+"</u></b><br><span id='KsEstimationD'>&nbsp;</span><td><b><u>"+culang.movementNextCity+"</u></b><br><span id=KsVilleProche></span>\
           </tr><tr align=center valign=top>\
           <td colspan=4 align=left><table border=0 bordercolor=black cellspacing=0 cellpadding=0 width=100% style='text-align:center'><tr><td rowspan=16><div id=RAAstatsource></div></td><td colspan=2><a href='javascript:void(0)' id=Ks_RAZ_Units title='"+culang.movementClearTroopsNote+"'>"+culang.mainTroopAmount+"</a></td><td>"+culang.movementAttackETA+"</td><td>"+culang.movementReinforceETA+"</td></tr>";
            for (r=1; r<16; r++){
                m += '<tr><td align=right><img height=20 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="RAAnbunit'+r+'" type=text size=7 value="0" ></td><td><span id="KsEstimationTT'+r+'">&nbsp;</span></td><td><span id="KsEstimationTZ'+r+'">&nbsp;</span></td></tr>';
            }
            var itemlist=[55,57,931,932];
            var Ksitems="";
            for(var i=0;i<itemlist.length;i++){
                Ksitems += "<img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/30/"+itemlist[i]+".jpg' /><input type=checkbox id='Ksitem_"+itemlist[i]+"'><span id='KsitemSpan_"+itemlist[i]+"'>" + unsafeWindow.ksoItems[itemlist[i]].count + "</span>&nbsp;";
            }
            m += "</table></td></tr>\
              <tr><td colspan=2><b><u>"+culang.mainKnights+"</u></b>: <SELECT id='RAApiKnight' type=list></select><br>"+Ksitems+"</td><td colspan=2><div id=Ksinfodest></div><center><input type=button value='"+culang.movementPlayerCheck+"' id=Ksrechdest></td></tr>\
              <tr><td colspan=4><b><div class=pdxStat>"+culang.movementHeadSavedAttacks+"</div></tr><tr><td colspan=2><select id=Ks_AT_Fav></select><input type=button value='"+culang.mainDelete+"' id=Ks_AT_Fav_Sup><input type=button value='"+culang.mainDeleteAll+"' id=Ks_AT_Fav_RESET></td><td colspan=2>"+culang.mainName+": <input type=type id='Ks_AT_Fav_Nom' size='10' maxlength='12' title='"+culang.movementSaveAttackName+"'>&nbsp;<input type=checkbox id=Ks_AT_Fav_Coo> <span title='"+culang.movementAutoAttackCoordNote+"'>"+culang.mainCoord+"</span> <input type=button value='"+culang.buttonSave+"' id=Ks_AT_Fav_ajou>\
              <tr><td colspan=4><b><div class=pdxStat>"+culang.movementHeadAutoAttack+"</div></tr><tr><td><input type=button id='KsActiveAttack' value='"+culang.mainAttack+" = "+culang.buttonOFF+"' ></td><td colspan=3><span id='KsCompAttack'></span></tr>\
              <tr><td><b><u>"+culang.mainArrival+"</u>:</b> <input type=text size=7 id='KsHorloge' value='" + Options.AttackHorloge + "' title='"+culang.movementAutoAttackArrivalNote+"'></td><td><input type=button value='"+culang.buttonSave+"' id='KsSaveAttack'></td><td><input type=button value='"+culang.buttonEdit+"' id='KsEditAttack' disabled></td></tr>\
              <tr><td colspan=4></td></tr></table>";
            t.cont.innerHTML = m;
            t.statpourRAA = ById ('statpourRAA');
            t.Favoris = ById('Ks_AT_Fav');
            t.Ksinfodest = ById('Ksinfodest');
            t.Ksrechdest = ById("Ksrechdest");
            // ById('boaideattaquer').addEventListener('click', function(){
            // window.open(homePage+" ");
            // } , false);
            t.Ksrechdest.addEventListener ('click', function() {
                t.rechercheDEST();
            }, false);
            function savedAttacks() {
                t.Favoris.innerHTML="<option value=''>-- "+culang.mainSelect+" --</option>";
                var lisf = Options.AttackFav;
                for (var m in lisf) {
                    var lis = lisf[m];
                    if (lis!=null)
                        t.Favoris.innerHTML+="<option value='"+m+"'>"+lis[0]+"</option>";
                }
            }
            ById("ptmarch_autoknight").addEventListener('click', function(){
                Options.marchautoknight = this.checked;
                saveOptions();
                t.show();
            },false);
            ById("Ks_AT_Fav_RESET").addEventListener ('click', function() {
                Options.AttackFav={};
                saveOptions();
                savedAttacks();
            }, false);
            ById("Ks_AT_Fav_Sup").addEventListener ('click', function() {
                numfav=ById("Ks_AT_Fav").value;
                if (numfav!="") {
                    Options.AttackFav[numfav]={};
                    delete Options.AttackFav[numfav];
                    saveOptions();
                    savedAttacks();
                }
            }, false);
            ById("Ks_RAZ_Units").addEventListener ('click', function() {
                for (r=1; r<15; r++) ById("RAAnbunit"+r).value=0;
            }, false);
            ById("Ks_AT_Fav_ajou").addEventListener ('click', function() {
                if (ById("Ks_AT_Fav_Nom").value=="") {
                    alert(""+culang.movementSaveAttackNamePopup+"");
                    return;
                }
                var a =ById("Ks_AT_Fav_Nom").value;
                Options.AttackFav[a]={};
                var lisf = Options.AttackFav[a];
                lisf[0]=ById("Ks_AT_Fav_Nom").value;
                for (r=1; r<16; r++) lisf[r]=ById("RAAnbunit"+r).value;
                if (ById("Ks_AT_Fav_Coo").checked) {
                    lisf[17]=t.destinationCityx.value;
                    lisf[18]=t.destinationCityy.value;

                }
                ById("Ks_AT_Fav_Coo").checked=false;
                ById("Ks_AT_Fav_Nom").value="";
                saveOptions();
                savedAttacks();
            }, false);
            ById("Ks_AT_Fav").addEventListener ('change', function() {
                numfav=ById("Ks_AT_Fav").value;
                if (numfav=="") {
                    for (r=1; r<16; r++) ById("RAAnbunit"+r).value=0;
                }else {
                    var lisf = Options.AttackFav[numfav];
                    for (var m in lisf) {
                        if(m>0 && m<16)
                            if (ById("RAAnbunit"+m)) ById("RAAnbunit"+m).value=lisf[m];
                        if (m==17)
                            if (lisf[m]>0)
                                t.destinationCityx.value=lisf[m];
                        if (m==18)
                            if (lisf[m]>0)
                                t.destinationCityy.value=lisf[m];
                    }
                }
            }, false);
            ById("Ksitem_55").addEventListener ('click', function() {
                ById("Ksitem_57").checked=false;
                t.estimerRes();
            }, false);
            ById("Ksitem_57").addEventListener ('click', function() {
                ById("Ksitem_55").checked=false;
                t.estimerRes();
            }, false);
            t.statutRAA = ById ('ptRAAStatus');
            t.destinationCityx = ById ('RAAtypetrpx');
            t.destinationCityy = ById ('RAAtypetrpy');
            t.destinationCityx.value = Options.Xrenfort;
            t.destinationCityy.value = Options.Yrenfort;
            if (ById ('maparea_map').style.display!="none") {
                t.destinationCityx.value = ById ('mapXCoor').value;
                t.destinationCityy.value = ById ('mapYCoor').value;
                t.rechercheDEST();
            }
            t.listeFavoris = ById ('listeFavori');
            t.listeFavoris.addEventListener ('change', t.SelectFavoris, false);
            t.chargelistelieux = ById ('Kschargelistelieux');
            t.chargelistelieux.addEventListener ('click', t.chercherFavoris, false);
            t.actionREN = ById ('RENaction');
            t.actionRENB = ById ('RENBaction');
            t.actionREE = ById ('REEaction');
            t.actionRAA = ById ('RAAaction');
            t.actionRAR = ById ('RARaction');
            t.actionREN.addEventListener ('click', function () { t.clickATTAQUEDo(2,0); }, false);
            t.actionRAA.addEventListener ('click',  function () { t.clickATTAQUEDo(4,0); }, false);
            t.actionRAR.addEventListener ('click',  function () { t.clickATTAQUEDo(5,0); }, false);
            t.actionRENB.addEventListener ('click',  function () { t.clickATTAQUEDo(2,1); }, false);
            t.actionREE.addEventListener ('click',  function () { t.clickATTAQUEDo(3,0); }, false);
            t.destinationCityx.addEventListener ('keyup', function () { t.estimerRes(); }, false);
            t.destinationCityy.addEventListener ('keyup', function () { t.estimerRes(); }, false);
            var dcp0 = new CdispCityPicker ('ptRAA0', ById('RAAsrcRptspeedcity'), false, t.clickRAACitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
            t.state = 1;
            t.estimerRes();
            t.KsAttackProg = ById ('KsAttackProg');
            t.KsHorloge = ById ('KsHorloge');
            t.KsSaveAttack = ById ('KsSaveAttack');
            t.KsEditAttack = ById ('KsEditAttack');
            t.KsCompAttack = ById ('KsCompAttack');
            t.KsActiveAttack  = ById ('KsActiveAttack');
            t.KsActiveAttack.addEventListener ('click', t.AutoattackOnOff, false);
            t.KsSaveAttack.addEventListener ('click', function () {
                var itemlist=[55,57,931,932];
                for(var i=0;i<itemlist.length;i++){
                    ById('KsitemSpan_'+itemlist[i]).checked=false;
                }
                t.enregistreAttack();
            }, false);
            if (Options.AttackCibleX!=0 && Options.AttackCibleY!=0) {
                t.KsEditAttack.disabled=false;
            }
            t.KsEditAttack.addEventListener ('click', function () {
                t.destinationCityx.value = Options.AttackCibleX;
                t.destinationCityy.value = Options.AttackCibleY;
                ById("RAApiKnight").value=Options.AttackKnight;
                nHtml.Click(ById("ptRAA0_"+Cities.byID[Options.AttackFromCity].idx));
                for (r=1; r<15; r++) {
                    ById("RAAnbunit"+r).value=Options.AttackUnits[r-1];
                }
            }, false);
            savedAttacks();
            if (Options.AttackOnOff) {
                t.KsActiveAttack.value=''+culang.mainAttack+' = '+culang.buttonON;
                t.activeAttack();
            }
        }
    },
    MapAjax : new CMapAjax(),
    rechercheDEST:function() {
        var t = Tabs2.Movement;
        t.Ksinfodest.innerHTML="<center>"+culang.movementPlayerCheckSearch+"</center>";
        var xcoord=t.destinationCityx.value;
        var ycoord=t.destinationCityy.value;
        t.MapAjax.request (xcoord, ycoord, 1, function(left, top, width, rslt) {
            map = rslt.data;
            for (k in map){
                if (xcoord==map[k].xCoord && ycoord==map[k].yCoord) {
                    var m="";
                    var uid=map[k].tileUserId;
                    if (uid==null || uid==0 || uid=="0") {
                        t.Ksinfodest.innerHTML="<center><span class='boldRed'>"+culang.mainNotAvailable+"</span></center>";
                        return;
                    }
                    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                    params.checkArr = uid;
                    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
                        method: "post",
                        parameters: params,
                        onSuccess: function (rslt) {
                            var p = rslt.data;
                            if (p[uid] == true) {
                                m = '<span style="color:green"><b>'+culang.movementPlayerCheckOn+'</b></span>';
                            } else {
                                m = '<center><span style="color:red"><b>'+culang.movementPlayerCheckOff+'</b></span>';
                            }
                            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                            params.pid = uid;
                            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
                                method: "post",
                                parameters: params,
                                onSuccess: function (rslt) {
                                    t.Ksinfodest.innerHTML="<center><b>" + rslt.playerInfo.displayName+"</b><BR>"+m;
                                },
                                onFailure: function (rslt) {},
                            });
                        },onFailure: function (rslt) {},
                    });
                }
            }
        });
    },
    AutoattackOnOff:function() {
        var t = Tabs2.Movement;
        t.KsCompAttack.innerHTML='';
        clearTimeout (t.KsAttackTimer);
        if (t.KsActiveAttack.value==''+culang.mainAttack+' = '+culang.buttonOFF+'') {
            t.KsActiveAttack.value=''+culang.mainAttack+' = '+culang.buttonON;
            Options.AttackOnOff = true;
            saveOptions();
            t.activeAttack();

        } else {
            Options.AttackOnOff = false;
            saveOptions();
            t.KsActiveAttack.value=''+culang.mainAttack+' = '+culang.buttonOFF;
        }
    },
    activeAttack:function() {
        var t = Tabs2.Movement;
        clearTimeout (t.KsAttackTimer);
        if (Options.AttackGoHorloge) {
            var depart=new Date()
            depart.setTime(Options.AttackGoHorloge);
            var now = unixTime()*1000;
            if (now >= Options.AttackGoHorloge) {
                t.KsCompAttack.innerHTML='<center><font color=red>'+culang.movementAutoAttackDone+'</font></center>';// ACTIONLOG
                t.destinationCityx.value = Options.AttackCibleX;
                t.destinationCityy.value = Options.AttackCibleY;
                ById("RAApiKnight").value=Options.AttackKnight;
                nHtml.Click(ById("ptRAA0_"+Cities.byID[Options.AttackFromCity].idx));
                for (r=1; r<16; r++) {
                    ById("RAAnbunit"+r).value=Options.AttackUnits[r-1];
                }
                t.clickATTAQUEDo(4,0);
                clearTimeout (t.KsAttackTimer);
                Options.AttackGoHorloge=null;
                Options.AttackOnOff = false;
                saveOptions();
                return;
            }
            if (now > depart.getTime()) {
                t.KsCompAttack.innerHTML='<center><font color=red>'+culang.movementAutoAttackNotPossible+'</font></center>';
                clearTimeout (t.KsAttackTimer);
                Options.AttackGoHorloge=null;
                saveOptions();
                return false;
            }
            t.KsAttackTimer=setTimeout(function(){
                var depart=new Date();
                depart.setTime(Options.AttackGoHorloge);
                var now = unixTime()*1000;
                var tempsrestant = depart.getTime() - now;
                t.KsCompAttack.innerHTML='<center><font color=red><b>'+culang.movementAutoAttackIn+' '+timestr(tempsrestant/1000)+'</b></font></center>';
                t.activeAttack();
            },1000);
        }
    },
    enregistreAttack : function() {
        var t = Tabs2.Movement;
        if (t.KsHorloge.value.match("^[0-9]{2}:[0-9]{2}:[0-9]{2}$")) {
            var horloge = t.KsHorloge.value;
            Options.AttackHorloge = horloge;
            var ndate=new Date();
            ndate.setHours(horloge.substr(0,2));
            ndate.setMinutes(horloge.substr(3,2));
            ndate.setSeconds(0);
            var atunits=new Array();
            for (r=1; r<16; r++) {
                atunits.push(parseInt(ById("RAAnbunit"+r).value));
            }
            Options.AttackUnits = atunits;
            Options.AttackFromCity = t.sourceCity.id;
            Options.AttackKnight = ById("RAApiKnight").value;
            Options.AttackCibleX = t.destinationCityx.value;
            Options.AttackCibleY = t.destinationCityy.value;

            var x1 = parseInt(t.sourceCity.x);
            var x2 = parseInt(t.destinationCityx.value);
            var y1 = parseInt(t.sourceCity.y);
            var y2 = parseInt(t.destinationCityy.value);
            var dist = distance (x1, y1, x2, y2);
            var tempplusgrand=0;
            for (r=1; r<16; r++){
                if (parseInt(ById("RAAnbunit"+r).value)>0) {
                    var m = estETA(dist, r, t.sourceCity.id,4);
                    if (tempplusgrand<m.ETA) tempplusgrand=m.ETA;
                }
            }
            var departtime=ndate.getTime() - (tempplusgrand*1000);
            var depart=new Date()
            depart.setTime(departtime);
            var now = unixTime()*1000;
            if (now > depart.getTime()) {
                t.KsAttackProg.innerHTML = ""+culang.movementMarchNotPossible+"";
                return false;
            }
            Options.AttackGoHorloge =  depart.getTime();
            saveOptions ();
            t.KsAttackProg.innerHTML = ""+culang.movementAutoAttackSend+" " + Options.AttackCibleX + ","+ Options.AttackCibleY +" "+culang.movementAutoAttackSend2+"";
            t.KsEditAttack.disabled=false;
        } else {
            t.KsAttackProg.innerHTML = ""+culang.movementWrongTimeFormat+"";
        }
    },
    clickATTAQUEDo: function(typemarche, bouffe) {
        var t = Tabs2.Movement;
        var totalunit=0;
        if (typemarche==3 && ById("RAAnbunit3").value==0) ById("RAAnbunit3").value=1;
        for (r=1; r<16; r++){
            if (typemarche==3 && r!=3) {
                ById("RAAnbunit"+r).value=0;
            }
            if (parseInt(ById("RAAnbunit"+r).value) > parseInt(ById("RAAdestunit"+r).value)) {
                ById("RAAnbunit"+r).style.backgroundColor="red";
                return false;
            }
            totalunit=totalunit+parseInt(ById("RAAnbunit"+r).value);
            ById("RAAnbunit"+r).style.backgroundColor="";
        }
        var errMsg = "";
        if (isNaN (t.destinationCityx.value) ||t.destinationCityx.value<0 || t.destinationCityx.value>749)
            errMsg = ""+culang.movementXMustBe+"<BR>";
        if (isNaN (t.destinationCityy.value) || t.destinationCityy.value<0 || t.destinationCityy.value>749)
            errMsg += ""+culan.movementYMustBe+"<br>";

        if (ById("RAApiKnight").value==0 && typemarche==4) {
            errMsg += ""+culang.movementErrorSelectKnight+"<BR>";
        }
        if (errMsg != "") {
            t.statutRAA.innerHTML = "<FONT COLOR=#550000>"+ errMsg +"</font>";
            return;
        }
        var x=t.destinationCityx.value;
        var y=t.destinationCityy.value;
        t.SaveCoordsOptions(x,y);
        var RInfo = getRallypointInfo(t.sourceCity.id);
        var maxtroupe = RInfo.maxMarchSize;
        var l_elem = ById("Ksitem_931");
        if(l_elem && l_elem.checked && parseInt(Seed.items["i931"]) > 0) {
            var maxtroupe = RInfo.maxMarchSize25;
        }
        var l_elem = ById("Ksitem_932");
        if(l_elem && l_elem.checked && parseInt(Seed.items["i932"]) > 0) {
            var maxtroupe = RInfo.maxMarchSize50;
        }
        if (totalunit==0) {
            t.statutRAA.innerHTML = '<FONT COLOR=#550000>'+culang.movementErrorNoTroops+'</font>';
            return;
        }
        if (totalunit > maxtroupe) {
            t.statutRAA.innerHTML = '<FONT COLOR=#550000>'+culang.movementErrorNoFreeSlots+' <span class="boldRed">'+maxtroupe+'</span> '+culang.movementErrorNoFreeSlots2+'</font>';
            return;
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);        
        var iused=new Array();
        var itemlist=[55,57,931,932];
        for(var i=0;i<itemlist.length;i++){

            var l_elem=ById("Ksitem_"+itemlist[i]);
            if(l_elem&&l_elem.checked&&parseInt(Seed.items["i"+itemlist[i]])>0){
                iused.push(itemlist[i]);
            }
        }
        var res=0;
        if (bouffe==1) {
            for (var i=1;i<16;i++) {
                res += parseInt(unsafeWindow.unitstats['unt'+i][5] * ById("RAAnbunit"+i).value * (1 + (0.10 * Seed.tech.tch10)));
            }
        }
        params.items=iused.join(",");
        params.cid= t.sourceCity.id;
        params.type = typemarche;
        params.xcoord = x;
        params.ycoord = y;
        if (typemarche==3)
            params.kid=0;
        else
            params.kid= ById("RAApiKnight").value;
        params.r1 = res;
        params.u1 = 0;
        params.u2 = 0;
        params.u3 = 0;
        params.u4 = 0;
        params.u5 = 0;
        params.u6 = 0;
        params.u7 = 0;
        params.u8 = 0;
        params.u9 = 0;
        params.u10 = 0;
        params.u11 = 0;
        params.u12 = 0;
        params.u13 = 0;
        params.u14 = 0;
        params.u15 = 0;
        if (typemarche!=3) {
            if (ById("RAAnbunit1").value>0) params.u1 = ById("RAAnbunit1").value;
            if (ById("RAAnbunit2").value>0) params.u2 = ById("RAAnbunit2").value;
            if (ById("RAAnbunit3").value>0) params.u3 = ById("RAAnbunit3").value;
            if (ById("RAAnbunit4").value>0) params.u4 = ById("RAAnbunit4").value;
            if (ById("RAAnbunit5").value>0) params.u5 = ById("RAAnbunit5").value;
            if (ById("RAAnbunit6").value>0) params.u6 = ById("RAAnbunit6").value;
            if (ById("RAAnbunit7").value>0) params.u7 = ById("RAAnbunit7").value;
            if (ById("RAAnbunit8").value>0) params.u8 = ById("RAAnbunit8").value;
            if (ById("RAAnbunit9").value>0) params.u9 = ById("RAAnbunit9").value;
            if (ById("RAAnbunit10").value>0) params.u10 = ById("RAAnbunit10").value;
            if (ById("RAAnbunit11").value>0) params.u11 = ById("RAAnbunit11").value;
            if (ById("RAAnbunit12").value>0) params.u12 = ById("RAAnbunit12").value;
            if (ById("RAAnbunit13").value>0) params.u13 = ById("RAAnbunit13").value;
            if (ById("RAAnbunit14").value>0) params.u14 = ById("RAAnbunit14").value;
            if (ById("RAAnbunit15").value>0) params.u15 = ById("RAAnbunit15").value;
        }else {
            params.u3 = ById("RAAnbunit3").value;
            ById("RAAnbunit3").value=0;
        }
        t.actionRAA.disabled=true;
        t.actionREN.disabled=true;
        t.actionREE.disabled=true;
        t.statutRAA.innerHTML = "<center><i><b>"+culang.movementInWork+"</b></i></center>";
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var t = Tabs2.Movement;
                var rslt = transport;
                if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unsafeWindow.unixtime();
                    var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                    for(i = 0; i <= unitsarr.length; i++){
                        if(params["u"+i]){
                            unitsarr[i] = params["u"+i];
                        }
                    }
                    var resources=new Array();
                    resources[0] = params.gold;
                    for(i=1; i<=4; i++){
                        resources[i] = params["r"+i];
                    }
                    var currentcityid =  t.sourceCity.id;
                    unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                    // unsafeWindow.update_seed(rslt.updateSeed)
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};

                    for(var i=0;i<iused.length;i++){
                        Seed.items["i"+iused[i]]=parseInt(Seed.items["i"+iused[i]])-1;unsafeWindow.ksoItems[iused[i]].subtract();
                    }
                    var typeattaque = "";
                    switch (typemarche){
                        case 2:
                            typeattaque="<span class='boldGreen'>"+culang.movementReinforceOK+"</span>";
                            break;
                        case 3:
                            typeattaque="<span class='boldGreen'>"+culang.movementScoutOK+"</span>";
                            break;
                        case 4:
                            typeattaque="<span class='boldRed'>"+culang.movementAttackOK+"</span>";
                            break;
                        case 5:
                            typeattaque="<span class='boldGreen'>"+culang.movementReassignOK+"</span>";
                            break;
                        default:
                            typeattaque="<span class='boldGreen'>"+culang.movementMarchOK+"</span>";
                    }
                    t.statutRAA.innerHTML = "<center><font size='3px'><i><b>"+typeattaque+"</b></i></font></center>";
                    t.actionRAA.disabled=false;
                    t.actionREE.disabled=false;
                    t.actionREN.disabled=false;
                    t.clickRAACitySourceSelect(t.sourceCity);
                } else {
                    if (rslt.user_action) {
                        t.statutRAA.innerHTML ="<font color=red size='3px'><b"+culang.movementCaptchaAlert+"<b></font>";
                        t.actionRAA.disabled=false;
                        t.actionREN.disabled=false;
                        t.actionREE.disabled=false;
                    } else {
                        t.statutRAA.innerHTML ="<font color=red size='3px'><b><i>"+culang.movementErrorTryAgain+"</i></b></font>";
                        if (rslt.msg) {
                            t.statutRAA.innerHTML +="<br><font color=black size='2px'>" + rslt.msg +"</font>";

                            t.actionRAA.disabled=false;
                            t.actionREN.disabled=false;
                            t.actionREE.disabled=false;
                        }else{
                            t.statutRAA.innerHTML +="<br><center>"+culang.mainError+"</center></font>";
                            t.actionRAA.disabled=false;
                            t.actionREN.disabled=false;
                            t.actionREE.disabled=false;
                        }
                    }
                }
            },
            onFailure: function () {
                var t = Tabs2.Movement;
                t.statutRAA.innerHTML ="<font color=red size='3px'><b><i>"+culang.movementErrorTryAgain+"</i></b></font>";
                t.actionRAA.disabled=false;
                t.actionREN.disabled=false;
                t.actionREE.disabled=false;
            }
        });
    },
    estimerRes: function() {
        var t = Tabs2.Movement;
        var x1 = parseInt(t.sourceCity.x);
        var x2 = parseInt(t.destinationCityx.value);
        var y1 = parseInt(t.sourceCity.y);
        var y2 = parseInt(t.destinationCityy.value);
        var dist = distance (x1, y1, x2, y2);
        ById("KsEstimationD").innerHTML = '<b>' + dist + '</b>&nbsp;<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ t.destinationCityx.value +','+ t.destinationCityy.value +')</a>';
        for (r=1; r<16; r++){
            var m = estETA(dist, r, t.sourceCity.id,4);
            ById("KsEstimationTT"+r).innerHTML = "<b>" + m.etaStr + "</b>";
            var m = estETA(dist, r, t.sourceCity.id,2);
            ById("KsEstimationTZ"+r).innerHTML = "<b>" + m.friendEtaStr + "</b>";
        }
        var closestDist=999999;
        var closestLoc=null;
        var closestNum=1;
        for (var c=0; c<Cities.numCities; c++){
            var city = Cities.cities[c];
            var dist=distance(city.x,city.y,x2,y2);
            if(dist<closestDist) {
                closestDist=dist;
                closestLoc=city.x +','+ city.y;
                closestNum=c+1;
            }
        }
        ById("KsVilleProche").innerHTML='<input type="submit" value="'+closestNum+'" class="castleBut castleButNon">'
    },
    SelectFavoris:function() {
        var t = Tabs2.Movement;
        if (t.listeFavoris.value!='') {
            var valeur=t.listeFavoris.value;
            var x=valeur.substr(0, valeur.lastIndexOf(','));
            var y=valeur.substr(valeur.lastIndexOf(',')+1, valeur.length);
            t.destinationCityx.value = x;
            t.destinationCityy.value = y;
        }
        t.estimerRes();
    },
    chercherFavoris: function() {
        var t = Tabs2.Movement;
        var myA = getMyAlliance ();
        if (myA[0]!=0) {
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.perPage = 100;
            params.allianceId = myA[0];
            params.type = 'might';
            params.page = 1;
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    if (rslt.ok){
                        var z=0;
                        var m="";
                        for (var i=0; i<rslt.results.length; i++){
                            p = rslt.results[i];
                            if (p.userId != 0){
                                for (var c=0; c<p.cities.length; c++){
                                    if (Seed.player.name!=p.displayName) {
                                        m += "<option value='" + p.cities[c].xCoord + ","+ p.cities[c].yCoord+"'>" + p.displayName + " - "+culang.mainCity+" " + (c+1) + " - " + p.cities[c].xCoord + "," + p.cities[c].yCoord+"</option>";
                                    }
                                }
                            }
                        }
                        t.listeFavoris.innerHTML="<option value=''>-- "+culang.mainSelect+" --</option>"+m;
                    }
                },
                onFailure: function (rslt) {
                    t.listeFavoris.innerHTML="<option>"+culang.mainError+"</option>";
                },
            });
        } else {
            t.listeFavoris.innerHTML="<option>"+culang.movementSelectErrorNoAlliance+"</option>";
        }
    },
    SaveCoordsOptions: function(x,y) {
        Options.Xrenfort = x;
        Options.Yrenfort = y;
        saveOptions ();
    },
    clickRAACitySourceSelect : function (city){
        var t = Tabs2.Movement;
        if (t.sourceCity!=city) {
            t.sourceCity = city;
        }
        var m="";
        m="<table cellspacing=0 cellpadding=0 width=80%><tr><td colspan=2><b><u>"+culang.mainTroopAmount+"</u></b></tr>";
        var cityID = 'city'+ t.sourceCity.id;
        for (r=1; r<16; r++){
            m += '<tr><td align=right><img title="'+unsafeWindow.unitcost['unt'+r][0]+'" height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td>\
             <td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="RAAdestunit'+r+'" type=text size=7 readonly value="'+parseInt(Seed.units[cityID]['unt'+r])+'">&nbsp;\
             <input type=button value=">" id="RAApdestunit'+r+'"  style="border:1px solid black;height:16px;font-size:11px;"></td></tr>';
        }
        m += "</table>";
        ById("RAAstatsource").innerHTML = m;
        var knt = new Array();
        for (k in Seed.knights['city' + t.sourceCity.id]){
            if (Seed.knights['city' + t.sourceCity.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.sourceCity.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["politicsKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["combatKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["intelligenceKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"]){
                knt.push ({
                    Name:   Seed.knights['city' + t.sourceCity.id][k]["knightName"],
                    Combat:    Seed.knights['city' + t.sourceCity.id][k]["combat"],
                    ID:    Seed.knights['city' + t.sourceCity.id][k]["knightId"],
                });
            }
        }
        knt = knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
        ById('RAApiKnight').innerHTML="";
        var o = document.createElement("option");
        o.text = uW.g_js_strings.modal_attack.dchooseknightd;
        o.value = 0;
        ById("RAApiKnight").options.add(o);
        for (k in knt){
            if (knt[k]["Name"] !=undefined){
                var o = document.createElement("option");
                o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +')')
                o.value = knt[k]["ID"];
                ById("RAApiKnight").options.add(o);
            }
        }
        if (ById('RAApiKnight').options.length>0) {
            if(Options.marchautoknight)
                ById('RAApiKnight').selectedIndex=1;
        }

        var itemlist=[55,57,931,932];
        for(var i=0;i<itemlist.length;i++){
            ById('KsitemSpan_'+itemlist[i]).innerHTML = unsafeWindow.ksoItems[itemlist[i]].count;
        }
        for (r=1; r<16; r++){
            ById("RAApdestunit"+r).addEventListener ('click', function() {
                var nomcha=this.id.replace("RAApdest","RAAdest");
                var nomcha2=this.id.replace("RAApdestunit","RAAnbunit");
                ById(nomcha2).value=0;
                var RInfo = getRallypointInfo(t.sourceCity.id);
                var maxtroupe = RInfo.maxMarchSize;
                var l_elem = ById("Ksitem_931");
                if(l_elem && l_elem.checked && parseInt(Seed.items["i931"]) > 0) {
                    var maxtroupe = RInfo.maxMarchSize25;
                }
                var l_elem = ById("Ksitem_932");
                if(l_elem && l_elem.checked && parseInt(Seed.items["i932"]) > 0) {
                    var maxtroupe = RInfo.maxMarchSize50;
                }
                var nbunitto=0;
                for (r=1; r<16; r++) {
                    nbunitto+=parseIntNan(ById("RAAnbunit"+r).value);
                }
                var libre = parseIntNan(maxtroupe - nbunitto);
                if (ById(nomcha).value>=libre) {
                    ById(nomcha2).value = libre;
                }  else {
                    ById(nomcha2).value= ById(nomcha).value;
                }
            }, false);
        }
        if (t.sourceCity!=city) {
            for (r=1; r<16; r++){
                ById("RAAnbunit"+r).value="0";
            }
        } else {
            for (r=1; r<16; r++){
                if (ById("RAAnbunit"+r).value=="") ById("RAAnbunit"+r).value="0";
                if (ById("RAAdestunit"+r).value=="") ById("RAAdestunit"+r).value="0";
                if (parseInt(ById("RAAnbunit"+r).value)>parseInt(ById("RAAdestunit"+r).value)) {
                    ById("RAAnbunit"+r).value="0";
                }
            }
        }
        t.estimerRes();
    },
}

//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/Gifts.js">
/************************************************************************************
 *                        KOC POWER - TABS2 GIFTS                                        *
 ************************************************************************************/
Tabs2.Gifts = {
    cont : null,
    kdodisp:{},
    amis: [],
    init : function (){
        var t = Tabs2.Gifts;
        t.cont = document.createElement('div');
        return t.cont;
    },
    getContent : function (){
        var t = Tabs2.Gifts;
        return t.cont;
    },
    hide : function (){
        var t = Tabs2.Gifts;
    },
    show : function (){
        var t = Tabs2.Gifts;
        var  m = "<DIV class=pdxStat>"+culang.giftsHead+"</div>";
        m+="<br>"+culang.giftsGifts+" <select id=KsKdoSel>";
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = "GiftItems";
        params.action = "getGiftItems";
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok){
                    t.kdodisp = rslt.giftItems;
                    for (k in t.kdodisp) {
                        if (t.kdodisp[k].itemId) {
                            m+="<option value='"+t.kdodisp[k].itemId+"' "+ (Options.KDODef==t.kdodisp[k].itemId?'SELECTED ':'') +">"+unsafeWindow.ksoItems[t.kdodisp[k].itemId].name+"</option>";
                        }
                    }
                    m+="</select>&nbsp;";
                    m+="<input type='button' value='"+culang.giftsButtonSend+"' id=KsKdoSendBtn><HR><div style='max-height:1000px;' id=KsKdoResult></div>";
                    t.cont.innerHTML = m;
                    ById("KsKdoSel").addEventListener('change', function(e){ Options.KDODef=ById("KsKdoSel").value;saveOptions(); },false);
                    ById("KsKdoSendBtn").addEventListener('click', function(e){ t.listMembers(); },false);
                }
            }
        });
    },
    
    listMembers:function() {
        var t = Tabs2.Gifts;
        t.amis=[];
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = "allianceGifting\\AllianceGiftingServiceAjax";
        params.action = "getRecipients";
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                var rsp=rslt.recipients;
                if (!Options.KDODefUsers) {Options.KDODefUsers = []; saveOptions();}
                var m = '<table>';
                var c = 0;
                for (k in rsp) {
                    var member = rsp[k];
                    if (member.userId) {
                        c++;
                        if (c == 1) m+='<tr>';
                        if (Options.KDODefUsers.contains(member.userId)) {
                            m+='<td><input id="KsKdo_'+member.userId+'" type="checkbox" checked></td>';            
                        } else {
                            m+='<td><input id="KsKdo_'+member.userId+'" type="checkbox"></td>';                        
                        }
                        if (member.playerSex == 'F') {
                            m+='<td><img height="30" src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/avatars/v2/50/f'+member.avatarId+'.png"></td>';
                            m+='<td width="150">'+uW.g_js_strings.commonstr.lady+' '+member.displayName+'</td>';
                        } else {
                            m+='<td><img height="30" src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/avatars/v2/50/m'+member.avatarId+'.png"></td>';
                            m+='<td width="150">'+uW.g_js_strings.commonstr.lord+' '+member.displayName+'</td>';
                        }
                        if (c == 4) {
                            m+='</tr>';
                            c = 0;
                        }
                        t.amis.push(member.userId);
                    }
                }
                m+= '</tr></table>';
                m+= '<br><b>'+rslt.freeSlot+' '+culang.giftsfreeSlot+'&nbsp;<span id="KsKdoCounter"></span></b><br>';
                m+= "<br><input type='submit' value='"+culang.giftsButtonSend+"' id='KsKdoSendBtnFinal'>&nbsp;<span id='KsKdoResult2'></span><br><br>";
                ById("KsKdoResult").innerHTML=m;
                //ById("KsKdoResult").innerHTML+= '<pre>'+inspect(rslt,9)+'</pre>';
                ById("KsKdoSendBtnFinal").addEventListener('click', function(e){ t.sendGift(); },false);
                var counter = 0;
                for (k in rsp) {
                    var member = rsp[k];
                    if (member.userId) {
                        var m = ById("KsKdo_"+member.userId);
                        if (m.checked) {
                            m.parentNode.style.backgroundColor = 'rgb(255, 255, 180)';
                            m.parentNode.nextSibling.style.backgroundColor = 'rgb(255, 255, 180)';
                            m.parentNode.nextSibling.nextSibling.style.backgroundColor = 'rgb(255, 255, 180)';
                            counter++;
                        } else {
                            m.parentNode.style.backgroundColor = 'rgb(246, 243, 236)';
                            m.parentNode.nextSibling.style.backgroundColor = 'rgb(246, 243, 236)';
                            m.parentNode.nextSibling.nextSibling.style.backgroundColor = 'rgb(246, 243, 236)';
                        }
                        ById("KsKdo_"+member.userId).addEventListener('click', function(e){ 
                            var t = Tabs2.Gifts;
                            var id = this.id.split('_')[1];
                            if (this.checked) {
                                Options.KDODefUsers.push(id);
                                this.parentNode.style.backgroundColor = 'rgb(255, 255, 180)';
                                this.parentNode.nextSibling.style.backgroundColor = 'rgb(255, 255, 180)';
                                this.parentNode.nextSibling.nextSibling.style.backgroundColor = 'rgb(255, 255, 180)';
                            } else {
                                for (var i = 0; i < Options.KDODefUsers.length; i++) {
                                    if (Options.KDODefUsers[i] == id) {
                                        Options.KDODefUsers.splice(i,1);
                                        break;
                                    }
                                }
                                this.parentNode.style.backgroundColor = 'rgb(246, 243, 236)';
                                this.parentNode.nextSibling.style.backgroundColor = 'rgb(246, 243, 236)';
                                this.parentNode.nextSibling.nextSibling.style.backgroundColor = 'rgb(246, 243, 236)';
                            }
                            saveOptions();
                            var counter = 0;
                            for (var i = 0; i < t.amis.length; i++) {
                                var m = ById("KsKdo_"+t.amis[i]);
                                if (m.checked) counter++;
                            }
                            var rep = {'counter': counter};
                            ById("KsKdoCounter").innerHTML = culang.giftscounter.mreplace(rep);
                        },false);
                    }
                }
                if (counter > 0) {
                    var rep = {'counter': counter};
                    ById("KsKdoCounter").innerHTML = culang.giftscounter.mreplace(rep);
                }
            },
        });
    },
    
    sendGift: function() {
        var t = Tabs2.Gifts;
        var counter = 0;
        if (Options.KDODefUsers.length > 0) {
            var amis = "";
            for (var i = 0; i < Options.KDODefUsers.length; i++) {
                if (t.amis.contains(Options.KDODefUsers[i])) {
                    amis += Options.KDODefUsers[i] + "|";
                    counter++;
                }
            }
        }
        if (counter > 0) {
            amis = amis.substring(0,amis.length-1);
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.ctrl = "allianceGifting\\AllianceGiftingServiceAjax";
            params.action = "sendGift";
            params.itemId=Options.KDODef;
            params.recipients = amis;
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",  parameters: params,
                onSuccess: function (rslt) {
                    ById("KsKdoResult2").innerHTML="<span class=boldGreen>"+culang.giftsResultOK+"</span><span class=boldRed>"+counter + "</span><span class=boldGreen> "+culang.giftsResultOK2+"</span>";
                },
            });
        } else {
            ById("KsKdoResult2").innerHTML="<span class=boldRed>"+culang.giftsNotOK+"</span>";
        }
    },
}
//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/Resources.js">
/************************************************************************************
 *                        KOC POWER - TABS2 COURT                                        *
 ************************************************************************************/
Tabs2.Resources = {
    cont:null,
    resource:null,
    users : [],
    doList : [], // list of gifts to accept
    accepting : false,
    city : null,
    total : {gold:0, 1:0, 2:0, 3:0, 4:0},

    init : function (){
        var t = Tabs2.Resources;
        t.resource = {1:unsafeWindow.g_js_strings.commonstr.food, 
                                    2:unsafeWindow.g_js_strings.commonstr.wood, 
                                    3:unsafeWindow.g_js_strings.commonstr.stone, 
                                    4:unsafeWindow.g_js_strings.commonstr.ore};
        this.cont = document.createElement('div');
        return this.cont;
    },
    show : function (){
        var t = Tabs2.Resources;
        this.cont.style.overflowY = 'auto';
        this.cont.innerHTML = '<DIV class=pdxStat>'+culang.ressourceHead+'</div><TABLE cellpadding=0 cellspacing=0 class=pdxTab width=100%><TR><TD align=center><INPUT id="pballlist" type=submit value="'+unsafeWindow.g_js_strings.commonstr.alliance+'" \><INPUT id="pballlist2" type=submit value="'+culang.mainFriends+'" \></td></tr></table>\
    <DIV id=resDiv style="width:100%; max-height:300px;">';
        ById('pballlist').addEventListener ('click', function() { t.e_clickfetchlist(1); }, false);
        ById('pballlist2').addEventListener ('click', function() { t.e_clickfetchlist(2); }, false);
    },

    hide : function (){
    },

    progress : function (msg, span, add){
        if(add)
            ById(span).innerHTML+=msg;
        else
            ById(span).innerHTML=msg;
    },

    e_clickfetchlist : function  (tt){     // (also cancel accepting)
        var t = Tabs2.Resources;
        t.users = [];
        if (t.accepting){
            ById('pballlist').value = ''+unsafeWindow.g_js_strings.commonstr.alliance+'';
            ById('resDiv').innerHTML+= '<BR><SPAN class=boldRed>'+culang.mainCanceled+'</span>';
            t.accepting = false;
            return;
        }
        if (tt==1) ById('resDiv').innerHTML = '<div class=pdxStat>'+culang.ressourceCheckCourtsAlliace+'</div>'+culang.ressourceSearchAlliance+' <span id=pbResUserListCount></span>';
        if (tt==2) ById('resDiv').innerHTML = '<div class=pdxStat>'+culang.ressourceCheckCourtsFriends+'</div>'+culang.ressourceSearchFriends+' <span id=pbResUserListCount></span>';

        t.fetchUserList (tt, gotUserList);
        function gotUserList(userList){
            if(userList.length < 1){
                listGifts();
                return;
            }
            ById('resDiv').innerHTML += '<BR><b><i>'+culang.ressourceCheckCourts+'</i></b> <span id=pbResUserAvailCount></span>';
            t.checkDailyAction(userList, listGifts);
        }

        function listGifts (){
            t.city = Cities.cities[0];
            var m = '<DIV class=pdxStat><CENTER>'+culang.mainPlayer+': '+ t.users.length +'</center></div>';
            if (t.users.length<1){
                ById('resDiv').innerHTML = m + '<BR><CENTER><i><b>'+culang.ressourceSearchNone+'</b></i></center>';
                return;
            }
            m += '<TABLE class=pdxTab align=center><TR><TD align=right><b>'+culang.mainCastle+'</b>: </td><TD id=pbrescityselspan></td></tr>\
      <TR><TD align=right>'+culang.mainRessources+': </td><TD>'
                + htmlSelector (t.resource, Options.getResType, 'id=pbResColType')
                + '</td></tr><TR><TD>'+culang.mainPlayer+': </td><TD width=250><INPUT type=submit id=pbResDo value="'+culang.buttonRessourceAccept+'">\
    &nbsp; <SPAN id=pbResNone class=boldRed></span></td></tr></table><TABLE class=pdxTab><TR valign=top><TD>\
    <INPUT id=pbResButAll type=submit value="'+culang.mainAll+'" style="width:100%; margin-bottom:5px"><BR><INPUT id=pbResButNone type=submit value="'+culang.mainNone+'"></td>\
    <TD width=10></td><TD><TABLE cellpadding=0 cellspacing=0 class=ksTabLined>\
    <TBODY id=pbResTbody style="width: 400px; overflow:auto; display:block;">\
    <TR style="font-weight:bold; background:white"><TD><b><u>'+culang.mainName+'</u></b></td><TD><b><u>'+uW.g_js_strings.commonstr.might+'</u></b></td><TD width=20></td></tr>';
            for (var i=0; i<t.users.length; i++){
                m += '<TR><TD><INPUT type=checkbox id=pbrchk_'+ i +'> &nbsp;'+ t.users[i].name +'</td><TD>'+ t.users[i].might +'</td></tr>';
            }
            ById('resDiv').innerHTML = m + '</tbody></table></td></tr></center></table>';
            new CdispCityPicker ('pbrescitysel', ById('pbrescityselspan'), true, t.e_CityButton, t.city.idx);
            ById('pbResDo').addEventListener ('click', t.getErDone, false);
            ById('pbResButAll').addEventListener ('click', t.e_butAll, false);
            ById('pbResButNone').addEventListener ('click', t.e_butNone, false);
            // var tbody = ById('pbResTbody');
            // tbodyScroller (tbody, getRemainingHeight (tbody, mainPop.div));
        }
    },

    e_CityButton : function (city, x, y){
        var t = Tabs2.Resources;
        t.city = city;
    },

    e_butAll : function (){
        var t = Tabs2.Resources;
        for (var i=0; i<t.users.length; i++)
            ById('pbrchk_'+i).checked = true;
    },

    e_butNone : function (){
        var t = Tabs2.Resources;
        for (var i=0; i<t.users.length; i++)
            ById('pbrchk_'+i).checked = false;
    },

    getErDone : function (){
        var t = Tabs2.Resources;
        t.doList = [];
        ById('pbResNone').innerHTML = '';
        Options.getResType = ById('pbResColType').value;
        t.total = {gold:0, 1:0, 2:0, 3:0, 4:0};
        for (var i=0; i<t.users.length; i++){
            if (ById('pbrchk_'+i).checked)
                t.doList.push (t.users[i]);
        }
        if (t.doList.length==0){
            ById('pbResNone').innerHTML = ''+culang.ressourceNoneSelected+'';
            return;
        }
        t.accepting = true;
        ById('pballlist').value = ''+culang.ressourceAcceptStop+'';
        ById('resDiv').innerHTML = '<DIV id=rsltDiv style="text-align: center;"><div class="pdxStat">'+culang.ressourceAcceptNow+' <u>'+ t.doList.length +'</u> '+culang.ressourceAcceptNow2+'</div><BR></div>';
        t.acceptNext ();
    },


    allDone : function (msg){
        var t = Tabs2.Resources;
        msg += ''+unsafeWindow.g_js_strings.commonstr.gold+': '+addCommas(t.total.gold)+'<BR>';
        for(var i=1; i<=4; i++){
            msg += t.resource[i]+': '+addCommas(t.total[i])+'<BR>';
        }
        ById('rsltDiv').innerHTML += '<BR>' + msg;
        ById('pballlist').value = ''+unsafeWindow.g_js_strings.commonstr.alliance+'';
        t.accepting = false;
    },


    acceptNext : function (){
        var t = Tabs2.Resources;
        var gift = t.doList.shift();
        if (gift == null){
            t.allDone ('<div class=pdxStat>'+culang.ressourceAcceptHead+'</div>');
            return;
        }
        var acpDiv = ById('rsltDiv');
        var curDiv = document.createElement ('div');
        acpDiv.appendChild (curDiv);
        curDiv.innerHTML = '<i><u>'+culang.mainFrom+'</u></i> <span class="boldGreen">'+ gift.name +'</span>: ';
        var statSpan = document.createElement ('span');
        curDiv.appendChild (statSpan);
        statSpan.innerHTML = ' ';
        t.getCourtAction (gift, gotGiftData);

        function gotGiftData (rslt){
            if (!t.accepting)
                return;
            if (rslt.ok){
                var msg = rslt.gold +' '+unsafeWindow.g_js_strings.commonstr.gold+' '+culang.mainAnd+' '+rslt.resource +' '+ t.resource[rslt.resourcetype]+' ...<b>'+culang.mainOK+'</b>.';
                statSpan.innerHTML += msg;
                t.total.gold += rslt.gold;
                t.total[rslt.resourcetype] += rslt.resource;
                t.acceptNext ();
                return;
            }

            if (rslt.msg)
                msg = '<B>'+ rslt.msg + '</b>';
            else
                msg = '<SPAN class=boldRed>'+culang.mainError+': '+ rslt.ajaxErr +'</span>';

            curDiv.removeChild (statSpan);
            curDiv = document.createElement ('div');
            curDiv.className = 'indent25';
            acpDiv.appendChild (curDiv);
            curDiv.innerHTML = msg;
            t.acceptNext ();
        }

    },

    getMembersInfo : function (pageNo, notify) {
        var t = Tabs2.Resources;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        params.pageNo = pageNo;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/allianceGetMembersInfo.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify ({errMsg:'Ajax Comm Error'});
            },
        });
    },
    getFriendsInfo : function (notify) {
        var t = Tabs2.Resources;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getAppFriends.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify ({errMsg:'Ajax Comm Error'});
            },
        });
    },
    getDailyAction : function (uid, notify){
        var t = Tabs2.Resources;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        params.pid = uid;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify ({errMsg:'Ajax Comm Error'});
            },
        });
    },

    getCourtAction : function (gift, notify){
        var t = Tabs2.Resources;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        params.atype = Options.getResType;
        params.toid = gift.userId;
        params.givercityid = t.city.id;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/courtDoAction.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify (rslt);
            },
            onFailure: function (rslt) {
                notify ({errMsg:'Ajax Comm Error'});
            },
        });
    },

    checkDailyAction : function (userList, notify){
        var t = Tabs2.Resources;
        var count = 0;
        t.getDailyAction(userList[count].userId, parseViewCourt);

        function parseViewCourt (rslt){
            if (!rslt.ok || rslt.errMsg)
                notify ({errMsg:'Ajax Comm Error'});
            if(rslt.dailyActionFlag == 0)
                t.users.push(userList[count]);
            t.progress(count, 'pbResUserAvailCount');
            count++;
            if(count < userList.length){
                t.getDailyAction(userList[count].userId, parseViewCourt);
            } else {
                notify();
            }
        }
    },
    fetchUserList : function (tt, notify){
        var t = Tabs2.Resources;
        var userList = [];
        if (tt==1)
            t.getMembersInfo(1, parseAlliancePage);

        if (tt==2)
            t.getFriendsInfo(parseAlliancePage2);
        function parseAlliancePage (rslt){
            if (!rslt.ok || rslt.errMsg)
                notify ({errMsg:'Ajax Comm Error'});
            var users = rslt.memberInfo;
            for(var k in users){
                userList.push({userId:users[k].userId, name:users[k].name, might:users[k].prestige, type:'alliance'});
            }
            t.progress(userList.length, 'pbResUserListCount');
            if(rslt.currentPage < rslt.noOfPages){
                t.getMembersInfo((rslt.currentPage+1), parseAlliancePage);
            } else {
                notify(userList);
                //t.getFriendsInfo(parseAlliancePage2);
            }
        }


        function parseAlliancePage2 (rslt){
            if (!rslt.ok || rslt.errMsg)
                notify ({errMsg:'Ajax Comm Error'});
            var users = rslt.data;
            for(var k in users){
                if (users[k].userId!=undefined)
                    userList.push({userId:users[k].userId, name:users[k].displayName, might:users[k].might, type:'friends'});
            }
            t.progress(userList.length, 'pbResUserListCount');
            notify(userList);
        }

    },
    getContent : function (){
        var t = Tabs2.Resources;
        return t.cont;
    },
},
//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/Throne2.js">
/************************************************************************************
 *                        KOC POWER - TABS2 THRONE                                    *
 ************************************************************************************/
Tabs2.Throne = {
    myDiv : null,
    cont : null,
    passage:null,
    timer : null,
    filtre:"",
    tableau:[],
    filtre2:"",
    filtre3:"",
    filtre6:0,
    filtre7:false,
    filtre8:"",
    filtre4:Options.AllEffet,
    filtre5:Options.EffetRouge,
    init : function (){
        this.myDiv = document.createElement('div');
        return this.myDiv;
    },

    hide : function (){
        var t = Tabs2.Throne;

    },
    getContent : function (){
        return Tabs2.Throne.myDiv;
    },

    show : function (){
        var t = Tabs2.Throne;
        if (Options.salvageconfig.CityCity==undefined) Options.salvageconfig.CityCity=0;
        uW.Kssalvage=t.salvage;
        uW.KsequipItem=t.equipItem;
        uW.KsUnequipItem=t.UnequipItem;
        uW.KsRepair = t.Repair;
        uW.KsupgradeQualite = t.upgradeQualite;
        uW.KsupgradeLevel = t.upgradeLevel;
        t.cont = this.myDiv;
        var m="";
        var nb=0;
        var nbbroken=0;
        var k=Seed.throne.slotEquip[Seed.throne.activeSlot];
        var item;
        var faction;
        var items = uW.kocThroneItems;
        var sl=0;
        if (t.passage==null) {
            t.passage=1;
            var taille = 500; //uW.screen.height - mainPop2.getLocation().y - 450;
            m += '<DIV class=pdxStat>'+culang.throneHead+'</div><table style="background-color:transparent;max-width:100%;width:755px;" cellspacing=0 cellpadding=2><tr>\
         <td><input type=checkbox id=KsFiltre4ST> '+culang.throneShowAllEffect+' &nbsp;<input type=checkbox id=KsFiltre7ST> '+culang.throneRepairItems+' - '+culang.throneRedEffects+' <select id=Kslisteeffets></select>\
         <br>'+culang.throneUseAehterstones+' <span id=KsTroneCityCity></span>&nbsp;<span id=KsTroneCityCityS>\
         </tr></table>';
            m +='<DIV class=pdxStat>'+culang.throneQualityUpgradeNote2+'</div><DIV id=KsTroneAether style="width:100%;height:45px;max-height:45px;"></DIV><DIV class=pdxStat>'+culang.throneHeadEquippedItems+'</div><DIV id=KsTroneE style="width:100%;height:33px;max-height:33px;"></DIV><DIV class=pdxStat><span id=KsNbArticle></span></div><center><table style="background-color:transparent;max-width:95%;width:755px;" cellspacing=0 cellpadding=2>\
      <tr><td colspan=1 width=35>&nbsp;</td>\
      <td width=35><select id=KsFiltre8ST><option value="">-- '+culang.throneLevel+' --</option><option value=1>+1</option><option value=2>+2</option><option value=3>+3</option><option value=4>+4</option><option value=5>+5</option><option value=6>+6</option><option value=7>+7</option><option value=8>+8</option><option value=9>+9</option><option value=10>+10</option></select></td>\
      <td width=120><select id=KsFiltre2ST><option value="">-- '+culang.throneQuality+' --</option><option value="0">'+unsafeWindow.g_js_strings.throneRoom.simple+'</option><option value="1">'+unsafeWindow.g_js_strings.throneRoom.common+'</option><option value="2">'+unsafeWindow.g_js_strings.throneRoom.uncommon+'</option><option value="3">'+unsafeWindow.g_js_strings.throneRoom.rare+'</option><option value="4">'+unsafeWindow.g_js_strings.throneRoom.epic+'</option><option value="5">'+unsafeWindow.g_js_strings.throneRoom.wondrous+'</option></select></td>\
      <td width=80><select id=KsFiltreST><option value="">-- '+culang.throneFamily+' --</option><option value="briton">briton</option><option value="druid">druid</option><option value="fey">fey</option></select></td>\
      <td width=80><select id=KsFiltre3ST><option value="">-- '+culang.throneType+' --</option><option value="advisor">advisor</option><option value="banner">banner</option><option value="chair">chair</option><option value="table">table</option><option value="window">window</option><option value="trophy">thropy</option><option value="candelabrum">candelabrum</option></select></td>\
      <td width=250><select id=KsFiltre5ST></select></td>\
      <td width=80><input type=checkbox id=KsTroneInverse>'+culang.throneInvertOrder+'</td></tr></table><DIV id=KsTroneC style="width:100%;height:'+taille+'px; max-height:'+taille+'px; overflow-y:auto"></div><br>';
            t.cont.innerHTML = m;

            var dcp0 = new CdispCityPicker ('KsRCityC', ById('KsTroneCityCity'), false, function(c) { ById('KsTroneCityCityS').innerHTML=c.name;var t = Tabs2.Throne;Options.salvageconfig.CityCity=c.idx;saveOptions();t.show();}, Options.salvageconfig.CityCity);


            var liste = uW.cm.thronestats.effects;
            ById("Kslisteeffets").innerHTML="";
            var o = document.createElement("option");
            o.text = "-- "+culang.mainNone+" --";
            o.value = 0;
            ById("Kslisteeffets").options.add(o);
            for (k in liste){
                if (liste[k] !=undefined){
                    var o = document.createElement("option");
                    o.text = liste[k][1];
                    o.value = k;
                    ById("Kslisteeffets").options.add(o);
                }
            }
            ById("KsFiltre5ST").innerHTML="";
            var o = document.createElement("option");
            o.text = "-- "+culang.throneBonus+" --";
            o.value = 0;
            ById("KsFiltre5ST").options.add(o);
            for (k in liste){
                if (liste[k] !=undefined){
                    var o = document.createElement("option");
                    o.text = liste[k][1];
                    o.value = k;
                    ById("KsFiltre5ST").options.add(o);
                }
            }
            ById('Kslisteeffets').value=t.filtre5;
            ById("Kslisteeffets").addEventListener ('change', t.filtreaction, false);

            ById('KsFiltreST').value=t.filtre;
            ById('KsFiltreST').addEventListener ('change', t.filtreaction, false);
            ById('KsFiltre2ST').value=t.filtre2;
            ById('KsFiltre2ST').addEventListener ('change', t.filtreaction, false);
            ById('KsFiltre3ST').value=t.filtre3;
            ById('KsFiltre3ST').addEventListener ('change', t.filtreaction, false);
            ById('KsFiltre4ST').checked=t.filtre4;
            ById('KsFiltre4ST').addEventListener ('click', t.filtreaction, false);
            ById('KsFiltre5ST').value=t.filtre6;
            ById('KsFiltre5ST').addEventListener ('change', t.filtreaction, false);

            ById('KsFiltre7ST').checked=t.filtre7;
            ById('KsFiltre7ST').addEventListener ('click', t.filtreaction, false);
            ById('KsFiltre8ST').value=t.filtre8;
            ById('KsFiltre8ST').addEventListener ('click', t.filtreaction, false);

            ById('KsTroneInverse').checked=Options.TroneInverse;
            ById('KsTroneInverse').addEventListener ('click', function() {
                Options.TroneInverse = ById('KsTroneInverse').checked;

                saveOptions ();
                t.show();
            }, false);

        }
        m='<table style="background-color:transparent;width:755px;max-width:95%;" cellspacing=0 cellpadding=2>';
        t.tableau=[];
        for (var z in items) {
            if (items[z].id) {
                item=uW.kocThroneItems[items[z].id];
                if (item) {

                    t.tableau[sl]=items[z].id;
                    sl++
                }
            }
        }
        var lignauto = Seed.throne.rowNum * 5;
        if (Options.TroneInverse) t.tableau.reverse();
        var pastoucher = [];

        for (var nbslot=1;nbslot<=Seed.throne.slotNum;nbslot++) {
            B = Seed.throne.slotEquip[nbslot];
            for (var zzz in B) {
                if (uW.kocThroneItems[B[zzz]]) {
                    pastoucher.push(B[zzz]);
                }
            }
        }

        var nbl=t.tableau.length+1;

        var KstimeLeft=-1;
        if (Seed.queue_throne) {
            if (Seed.queue_throne.end)
                KstimeLeft = Seed.queue_throne.end - uW.unixtime();
        }

        for (var z=0;z<t.tableau.length;z++) {
            item=uW.kocThroneItems[t.tableau[z]];
            itemNr=0; for(z2 in uW.kocThroneItems) {itemNr++;if(z2==item.id)break;}
            nb++
            faction=item.faction;
            x=0;
            nbl--;
            if ( (t.filtre=="" || t.filtre==faction) && (t.filtre2=="" || t.filtre2==item.quality) && (t.filtre3=="" || t.filtre3==item.type) && (t.filtre7==false || (t.filtre7==item.isBroken || (t.filtre=true && Seed.queue_throne.itemId==item.id)))  && (t.filtre8=="" || t.filtre8==item.level)   )  {

                var ok=0;
                for (var u in item.effects) {
                    if (t.filtre6==item.effects[u].id) {
                        ok=1;
                    }
                }

                if (t.filtre6=="0" || ok==1) {
                    var styleez="";

                    if (item.isEquipped) {
                        equip="equip";
                        styleez="background-color:#DC9999";
                    }else{
                        equip="normal";
                    }

                    if (pastoucher.toString().indexOf(t.tableau[z])>-1 && equip=="normal")
                        styleez="background-color:#99DC99";

                    var styleauto="";
                    //if (upgradeData.item_upgrade[t.tableau[z]] || upgradeData.item_enhance[t.tableau[z]]) {
                    //       styleauto="background-color:#D9D988";
                    //       m+="<tr><td style='"+styleauto+";width:35px' title='En auto upgrade'>"
                    //      }else {
                    m+="<tr><td style='"+styleez+";width:35px'>"
                    //      }
                    if (Seed.queue_throne) {
                        if (Seed.queue_throne.itemId==item.id) {
                            nbbroken++
                            m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/modal/sm_hammer.png>";
                        } else {
                            if (item.isBroken) {
                                nbbroken++
                                m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/modal/sm_fail_overlay.png>";
                            } else {
                                m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+ faction+"/"+ faction+"_"+item.type+"_"+equip+"_1_5.png>";
                            }
                        }
                    } else {
                        if (item.isBroken) {
                            m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/modal/sm_fail_overlay.png>";
                        } else {
                            m+="<img title='"+getThroneItemName(item.id)+"' width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+ faction+"/"+ faction+"_"+item.type+"_"+equip+"_1_5.png>";
                        }
                    }
                    m+="</td>"
                    
                    m+="<td colspan=4 style='"+styleez+";width:250px'>";
                    m+=getThroneItemName(item.id)+"<br>";
                    m+="#"+itemNr+" / "+item.faction+" / "+item.type;
                    m+="</td>";
                    //<td style='"+styleez+";width:120px'>"+ item.createPrefix() + "</td><td style='"+styleez+";width:80px'>"+item.faction+"</td><td style='"+styleez+";width:80px'> "+item.type+"</td>";

                    m+="<td style='"+styleez+";width:300px'>";
                    for (var u in item.effects) {
                        x++;
                        L = item.effects[u];
                        if ((item.quality >= x && !t.filtre4) || t.filtre4) {
                            var coleur="";
                            var stylee="";
                            if (item.quality < x)
                                stylee="text-decoration:line-through";
                            if (t.filtre5==item.effects[u].id) stylee+=";color:#AA1111;font-weigth:bold";
                            effect = uW.cm.thronestats.effects[L.id];
                            tier = uW.cm.thronestats.tiers[L.id][L.tier];
                            var percent = + tier.base + (item.level * item.level + item.level) * + tier.growth * 0.5;
                            //percent = percent > 0 ? "+" + percent : + percent;
                            percent = Math.round(percent*100)/100;
                            typpee="";
                            for (l=0;l<effect["2"].length;l++){
                                typpee+=effect["2"][l];
                            }
                            m+="<span style='"+stylee+"'><font color="+coleur+">" + percent + "% " + effect[1] + " ("+typpee+")</font></span><bR>";
                        }
                    }

                    if ((Options.TroneInverse && nbl<=lignauto) || (!Options.TroneInverse && nb<=lignauto)) {
                        m+="</td><td style='"+styleez+"'><center>";

                        if (Seed.queue_throne && Seed.queue_throne.itemId==item.id) {
                            var timeLeft = Seed.queue_throne.end - uW.unixtime();
                            if (timeLeft<0) {
                                m+=""+culang.throneRepairDone+"</td></tr>";
                            } else {
                                m+=""+culang.throneRepairTime+"<br>"+timestr(timeLeft)+"";
                            }
                        }else{
                            if (item.isBroken) {
                                if (KstimeLeft<0) {
                                    m+="<a onclick='KsRepair("+t.tableau[z]+")' class='buttonv2 h20 blue'>"+culang.throneRepair+"</a>";
                                }

                            } else {
                                if (item.quality<5) {
                                    stoneenhance=uW.cm.thronestats["enhance"][item.quality+1].Stones;
                                    cityId='city'+Seed.cities[Options.salvageconfig.CityCity][0];
                                    if (parseIntNan(stoneenhance)<parseIntNan(Seed.resources[cityId]['rec5'][0])) {
                                        m+="<a onclick='KsupgradeQualite("+t.tableau[z]+")' class='buttonv2 h20 brown'  title='"+culang.throneQualityUpgradeNote+" "+stoneenhance+" "+culang.throneQualityUpgradeNote2+"'>+"+culang.throneQuality+"</a>";
                                    } else {
                                        //m+="<a class='buttonv2 h20 red' title='Besoin de "+stoneenhance+" pierres ether'>+Qualit&eacute;</a>";
                                    }
                                }
                                if (item.level<9) {
                                    stoneupgrade=uW.cm.thronestats["upgrade"][item.level+1].Stones;
                                    cityId='city'+Seed.cities[Options.salvageconfig.CityCity][0];
                                    if (parseIntNan(stoneupgrade)<parseIntNan(Seed.resources[cityId]['rec5'][0])) {
                                        m+="<a onclick='KsupgradeLevel("+t.tableau[z]+")' class='buttonv2 h20 brown' title='"+culang.throneQualityUpgradeNote+" "+stoneupgrade+" "+culang.throneQualityUpgradeNote2+"'>+"+culang.throneLevel+"</a>";
                                    }else{
                                        //m+="<a class='buttonv2 h20 red' title='Besoin de "+stoneenhance+" pierres ether'>+Niveau</a>";
                                    }
                                }
                                m+="<br><a onclick='Kssalvage("+t.tableau[z]+")' class='buttonv2 h20 red'>"+culang.mainDelete+"</a>";
                                if (equip=="normal")
                                    m+="<a onclick='KsequipItem("+t.tableau[z]+")' class='buttonv2 h20 blue'>"+culang.throneEquipItem+"</a>";
                                else
                                    m+="<a onclick='KsUnequipItem("+t.tableau[z]+")' class='buttonv2 h20 blue'>"+culang.throneUnequipItem+"</a>";
                            } // fin de isbroken
                        }
                    } else {
                        m+="</td><td style="+styleez+"><center><items><b>"+culang.throneNoSlots+"";
                    }
                    m+"</td></tr>";
                }
            }

        }
        ById("KsTroneC").innerHTML=m;
        // Equipement
        var effft="",faction={0:'advisor',1:'banner',2:'chair',3:'table',4:'window',5:'trophy',6:'candelabrum'};
        var zz="<center><table width=100%><tr>";
        for (var fp in faction) {
            equip="normal";
            effft="";
            var k=Seed.throne.slotEquip[Seed.throne.activeSlot];
            for (var tt in k) {
                if (uW.kocThroneItems[k[tt]])
                    if (uW.kocThroneItems[k[tt]].type==faction[fp]) {
                        var fr = uW.kocThroneItems[k[tt]].faction;
                        equip="normal";
                        x=0;
                        for (var u in uW.kocThroneItems[k[tt]].effects) {
                            x++;
                            if (uW.kocThroneItems[k[tt]].quality >= x) {
                                var ww=uW.cm.thronestats.tiers[uW.kocThroneItems[k[tt]].effects[u].id][uW.kocThroneItems[k[tt]].effects[u].tier];
                                var pourc = + ww.base + (uW.kocThroneItems[k[tt]].level * uW.kocThroneItems[k[tt]].level + uW.kocThroneItems[k[tt]].level) * + ww.growth * 0.5;
                                pourc = Math.ceil(pourc);
                                effft+= pourc + "% " + uW.cm.thronestats.effects[uW.kocThroneItems[k[tt]].effects[u].id][1]+ "&#013;";

                            }
                        }
                    }
            }
            zz+="<td width=30><img title='"+effft+"' align=absmiddle width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+fr+"/"+fr+"_"+faction[fp]+"_"+equip+"_1_5.png><td>"+faction[fp]+"</td>";
        }
        zz+="</tr></table>";
        ById("KsTroneE").innerHTML=zz;
        ById("KsNbArticle").innerHTML= nb + " "+culang.throneHeadEquippedItems2+" "+ nbbroken +" "+culang.throneHeadEquippedItems3+"";
        clearTimeout(t.citystattimer);
        t.citystat();
    },
    citystattimer:null,
    citystat:function() {
        var t = Tabs2.Throne;
        var zz="<TABLE class=ptTabLined cellspacing=0 style='margin-bottom:5px;'><tr><td></td>";
        var zx="";
        clearTimeout(t.citystattimer);
        for(var i=0; i<Cities.numCities; i++) {
            var cityID = 'city'+ Cities.cities[i].id;
            zz += "<TD width=81 align=center><B>"+ Cities.cities[i].name.substring(0,10) +'</b></td>';
            zx += "<TD width=81 align=center><B>"+ addCommas(parseIntNan(Seed.resources[cityID]['rec5'][0])) + "</b></td>";
        }
        zz+="</tr><tr><td><img height=18 src='"+IMGastone30+"'></td>"+zx;
        zz+="</table>";

        ById("KsTroneAether").innerHTML=zz;
        t.citystattimer=setTimeout(t.citystat,5000);

    },
    filtreaction: function() {
        var t = Tabs2.Throne;
        t.filtre = ById('KsFiltreST').value;
        t.filtre2 = ById('KsFiltre2ST').value;
        t.filtre3 = ById('KsFiltre3ST').value;
        t.filtre4 = ById('KsFiltre4ST').checked;
        t.filtre5 = ById('Kslisteeffets').value;
        t.filtre6 = ById('KsFiltre5ST').value;
        t.filtre7 = ById('KsFiltre7ST').checked;
        t.filtre8 = ById('KsFiltre8ST').value;
        Options.EffetRouge = t.filtre5;
        Options.AllEffet = t.filtre4;
        saveOptions ();
        t.show();

    },
    upgradeQualite:function(id) {
        var t = Tabs2.Throne;

        var currentcityid = Seed.cities[Options.salvageconfig.CityCity][0];

        var params = uW.Object.clone(uW.g_ajaxparams);
        params.action="upgradeQuality";
        params.ctrl="throneRoom\\ThroneRoomServiceAjax";
        params.throneRoomItemId=id;
        params.buffItemId=0;
        params.payment="aetherstone";
        params.cityId=currentcityid;
        uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
            onSuccess:function(transport) {
                var m = eval("(" + transport.responseText + ")");
                if (m.ok === true){
                    Seed.resources["city" + currentcityid].rec5[0] = Seed.resources["city" + currentcityid].rec5[0] - m.aetherstones;

                    var s = uW.kocThroneItems[id];
                    if (m.success) {
                        s.quality = m.item.quality;s.level = m.item.level;s.name = s.createName();
                    } else {
                        s.quality = m.item.quality;s.level = m.item.level;s.name = s.createName();
                        if (m.break) { s.brokenType = "quality"; }
                        s.isBroken = true;
                        s.name = s.createName();
                    }
                    t.show();
                }
            }
        });

    },
    upgradeLevel:function(id) {
        var t = Tabs2.Throne;
        var currentcityid = Seed.cities[Options.salvageconfig.CityCity][0];

        var params = uW.Object.clone(uW.g_ajaxparams);
        params.action="upgradeLevel";
        params.ctrl="throneRoom\\ThroneRoomServiceAjax";
        params.throneRoomItemId=id;
        params.buffItemId=0;
        params.payment="aetherstone";
        params.cityId=currentcityid;
        uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
            onSuccess:function(transport) {
                var m = eval("(" + transport.responseText + ")");
                if (m.ok === true){
                    Seed.resources["city" + currentcityid].rec5[0] = Seed.resources["city" + currentcityid].rec5[0] - m.aetherstones;
                    var s = uW.kocThroneItems[id];
                    if (m.success) {
                        s.quality = m.item.quality;s.level = m.item.level;s.name = s.createName();
                    } else {
                        s.quality = m.item.quality;s.level = m.item.level;s.name = s.createName();
                        if (m.break) { s.brokenType = "level"; }
                        s.isBroken = true;
                        s.name = s.createName();
                    }
                    t.show();
                }
            }
        });

    },
    Repair:function(id) {
        var t = Tabs2.Throne;
        var params = uW.Object.clone(uW.g_ajaxparams);
        params.action="timeRepair";
        params.ctrl="throneRoom\\ThroneRoomServiceAjax";
        params.throneRoomItemId=id;
        uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
            onSuccess:function(transport) {
                var m = eval("(" + transport.responseText + ")");
                if (m.ok === true){
                    Seed.queue_throne.start = uW.unixtime();
                    Seed.queue_throne.end = m.eta;
                    Seed.queue_throne.itemId = id;
                    uW.kocThroneItems[id].isBroken = false;
                    unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
                    t.show();
                }
            }
        });

    },
    equipItem: function(id) {
        var t = Tabs2.Throne;
        var params = uW.Object.clone(uW.g_ajaxparams);
        params.action="equipItem";
        params.ctrl="throneRoom\\ThroneRoomServiceAjax";
        params.itemId=id;
        params.presetId=Seed.throne.activeSlot;
        uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
            onSuccess:function(transport) {
                var m = eval("(" + transport.responseText + ")");
                if (m.ok === true){
                    uW.cm.ThroneView.clickItemEquip(uW.kocThroneItems[id]);
                    t.show();
                }
            }
        });
    },
    UnequipItem: function(id) {
        var t = Tabs2.Throne;
        var params = uW.Object.clone(uW.g_ajaxparams);
        params.action="unequipItem";
        params.ctrl="throneRoom\\ThroneRoomServiceAjax";
        params.itemId=id;
        params.presetId=Seed.throne.activeSlot;
        uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
            onSuccess:function(transport) {
                var m = eval("(" + transport.responseText + ")");
                if (m.ok === true){
                    unsafeWindow.cm.ThroneView.clickItemUnequip(uW.kocThroneItems[id]);
                    t.show();
                }
            }
        });
    },
    salvage: function(id) {
        var t = Tabs2.Throne;
        var params = uW.Object.clone(uW.g_ajaxparams);
        params.action="salvage";
        params.ctrl="throneRoom\\ThroneRoomServiceAjax";
        params.itemId=id;
        /*var cityid = 0;
         for (var k in Cities.byID) {
         if (Seed.resources["city"+k]["rec5"][0] < 1000000)
         {
         cityid = k;
         break;
         }
         }
         if (cityid == 0) cityid = Seed.cities[0][0];*/
        params.cityId=Seed.cities[Options.salvageconfig.CityCity][0];

        uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
            onSuccess:function(transport) {
                var m = eval("(" + transport.responseText + ")");
                if (m.ok){

                    unsafeWindow.kocThroneItems[id].salvage();
                    t.show();
                }else{

                }
            }
        });
    }
}
//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/Overview.js">
/************************************************************************************
 *                        KOC POWER - TABS OVERVIEW                                    *
 ************************************************************************************/
function getRallypointInfo(cityId) {
    var ret = {
        level: 0,
        maxMarches: 0,
        maxMarchSize: 0,
        maxMarchSize25: 0,
        maxMarchSize50: 0,
        usedSlots: 0,
    };
    var city = 'city'+ cityId;
    for (var o in Seed.buildings[city]) {
        var buildingType = parseInt(Seed.buildings[city][o][0]);
        var buildingLevel = parseInt(Seed.buildings[city][o][1]);
        if (buildingType == 12) {
            ret.level = parseInt(buildingLevel);
            if (parseInt(buildingLevel) == 12) {
                ret.maxMarches = 11;
            } else {
                ret.maxMarches = parseInt(buildingLevel);
            }
            if (uW.cm.PrestigeModel.isPrestige(cityId)) {
                var a = uW.cm.PrestigeModel.getPrestigeLevel(cityId);
                if (a > 0) {
                    var mm = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
                    k = uW.JSON.parse(mm),
                    o = k.values[a - 1][2],
                    ii = parseFloat(o);
                    ret.maxMarches = ret.maxMarches + ii;
                }
            }
            break;
        }
    }
    var e = 1;
    var f = uW.unixtime();
    if (Seed.playerEffects.aurasExpire && Seed.playerEffects.aurasExpire > f) e = 1.15;
    if (Seed.playerEffects.auras2Expire && Seed.playerEffects.auras2Expire > f) e = 1.3;
    var e25 = e + 0.25;
    var e50 = e + 0.5;        
    if (uW.cm.PrestigeModel.isPrestige(cityId)) {
        var b = uW.cm.PrestigeModel.getPrestigeLevel(cityId);
        if (b > 0) {
            var r = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
            m = uW.JSON.parse(r),
            u = m.values[b - 1][1],
            k = parseFloat(u);
            e *= k;
            e25 *= k;
            e50 *= k;
        }
    }
    var maxsend = parseInt(ret.level * 10000 * e);
    var maxsend25 = parseInt(ret.level * 10000 * e25);
    var maxsend50 = parseInt(ret.level * 10000 * e50);
    if (ret.level == 11) {
        var maxsend = parseInt(150000 * e);
        var maxsend25 = parseInt(150000 * e25);
        var maxsend50 = parseInt(150000 * e50);
    }
    if (ret.level == 12) {
        var maxsend = parseInt(200000 * e);
        var maxsend25 = parseInt(200000 * e25);
        var maxsend50 = parseInt(200000 * e50);
    }
    var q = uW.cm.ThroneController.effectBonus(66);
    if (q > 150) q = 150;
    ret.maxMarchSize = Math.round(maxsend * (1 + q / 100));
    ret.maxMarchSize25 = Math.round(maxsend25 * (1 + q / 100));
    ret.maxMarchSize50 = Math.round(maxsend50 * (1 + q / 100));
    //Blessing FILL_THE_RANKS
    var blessing = uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().FILL_THE_RANKS, cityId, {marchsize: true});
    ret.maxMarchSize = Math.round(ret.maxMarchSize * blessing);
    ret.maxMarchSize25 = Math.round(ret.maxMarchSize25 * blessing);
    ret.maxMarchSize50 = Math.round(ret.maxMarchSize50 * blessing);
    var slots = 0;
    for (var k in Seed.queue_atkp[city]){
        var m = Seed.queue_atkp[city][k];
        if (typeof (m) == 'object') slots++;
    }
    ret.usedSlots = slots;
    return ret;
}
 
function getResourceProduction (cityId){
    var ret = [0,0,0,0,0];
    var now = unixTime();

    var wilds = [0, 0, 0, 0, 0];
    var w = Seed.wilderness["city" + cityId];
    for (var k in w){
        var type = parseInt(w[k].tileType);
        if (type==10 || type==11)
            wilds[1] += parseInt(w[k].tileLevel);
        else
            wilds[type/10] += parseInt(w[k].tileLevel);
    }

    knight = 0;
    var s = Seed.knights["city" + cityId];
    if (s) {
        s = s["knt" + Seed.leaders["city" + cityId].resourcefulnessKnightId];
        if (s){
            var knight = parseInt(s.resourcefulness);
            if (parseInt(s.resourcefulnessBoostExpireUnixtime) > now)
                knight *= 1.25;
        }
    }
    var workerFactor = 1;
    var c = parseInt(Seed.citystats["city" + cityId]["pop"][0]);  // Current  population
    var w = parseInt(Seed.citystats["city" + cityId]["pop"][3]);  // Labor force
    if (w > c)
        workerFactor = c / w;

    for (var i=1; i<5; i++){
        var usage = Seed.resources["city" + cityId]["rec" + i];
        var items = 0;
        if (parseInt(Seed.playerEffects["r" + i + "BstExp"]) > now) {
            items = 0.25;
        }
        var tech = Seed.tech["tch" + i];
        ret[i] = parseInt((usage[2] * (1 + tech/10 + knight/100 + items + 0.05 * wilds[i]) * workerFactor + 100));
    }
    return ret;
}

function getWallInfo (cityId, objOut){
    objOut.wallSpaceUsed = 0;
    objOut.fieldSpaceUsed = 0;
    objOut.wallLevel = 0;
    objOut.wallSpace = 0;
    objOut.fieldSpace = 0;
    objOut.Crossbows = 0;
    objOut.CrossbowsTraining = 0;
    objOut.Trebuchet = 0;
    objOut.TrebuchetTraining = 0;
    objOut.Caltrops = 0;
    objOut.CaltropsTraining = 0;
    objOut.SpikedBarrier = 0;
    objOut.SpikedBarrierTraining = 0;
    objOut.Trap = 0;
    objOut.TrapTraining = 0;
    objOut.slotsBusy = 0;
    var b = Seed.buildings["city" + cityId];
    if (b.pos1==null)
        return;
    objOut.wallLevel = parseInt(b.pos1[1]);
    var spots = 0;
    for (var i=1; i<(objOut.wallLevel+1); i++)
        spots += (i * 500);
    objOut.wallSpace = spots;
    objOut.fieldSpace = spots;

    var fort = Seed.fortifications["city" + cityId];
    for (k in fort){
        var id = parseInt(k.substr(4));
        if (id == 53)
            objOut.Crossbows = parseInt(fort[k]);
        else if (id == 55)
            objOut.Trebuchet = parseInt(fort[k]);
        else if (id == 60)
            objOut.Trap = parseInt(fort[k]);
        else if (id == 61)
            objOut.Caltrops = parseInt(fort[k]);
        else if (id == 62)
            objOut.SpikedBarrier = parseInt(fort[k]);
        if (id<60)
            objOut.wallSpaceUsed += parseInt(unsafeWindow.fortstats["unt"+ id][5]) * parseInt(fort[k]);
        else
            objOut.fieldSpaceUsed += parseInt(unsafeWindow.fortstats["unt"+ id][5]) * parseInt(fort[k]);
    }
    var q = Seed.queue_fort["city"+cityId];
    if (q && q.length>0) {
        for (qi=0; qi<q.length; qi++) {
            objOut.slotsBusy++;
            if (q[qi][0]==53)
                objOut.CrossbowsTraining += parseInt(q[qi][1]);
            if (q[qi][0]==55)
                objOut.TrebuchetTraining += parseInt(q[qi][1]);
            if (q[qi][0]==60)
                objOut.TrapTraining += parseInt(q[qi][1]);
            if (q[qi][0]==61)
                objOut.CaltropsTraining += parseInt(q[qi][1]);
            if (q[qi][0]==62)
                objOut.SpikedBarrierTraining += parseInt(q[qi][1]);
        }
    }
}


Tabs.Overview = {
    tabOrder: TabOptions.toOverview,
    tabLabel: culang.tabLabelOverview,
    myDiv: null,
    craftitems : {},
    displayTimer : null,
    checkBox:null,
    defMode : {},
    checkBox1:null,
    Overview : function (){
    },

    init : function (div){
        var t = Tabs.Overview;
        for(var i=0; i < uW.recipelist[1].length; i++){
            var h = parseInt(uW.recipelist[1][i].output_item_id);
            t.craftitems[uW.recipelist[1][i].recipe_id] = h;
        }
        for(var i=0; i < uW.recipelist[3].length; i++){
            var h = parseInt(uW.recipelist[3][i].output_item_id);
            t.craftitems[uW.recipelist[3][i].recipe_id] = h;
        }
        t.myDiv = div;
        var str= '<DIV class=pdxStat2><a href="#" onclick="document.getElementById(\'statsTabOptions\').style.display=(document.getElementById(\'statsTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadStats+'</a></div>\
        <DIV id="statsTabOptions" style="display:none;">\
        <TABLE class=pdxTab>\
            <TR><TD width="20"><INPUT id=togShowTroops  type=checkbox /></td><TD width="300">'+culang.optionsStatsTabShowTroops+'</td><TD width="20"><INPUT id=togShowDefense  type=checkbox /></td><TD width="238">'+culang.optionsStatsTabShowDef+'</td></tr>\
            <TR><TD><INPUT type=checkbox id=togShowRes /></td><TD>'+culang.optionsStatsTabShowRes+'</td><TD><INPUT type=checkbox id=ptEnableReduireUnit /></td><TD>'+culang.optionsStatsTabShortValues+'</td></tr>\
            <TR><TD><INPUT type=checkbox id=togShowProduction /></td><TD>'+culang.optionsStatsTabShowResProduction+'</td><TD><input type=checkbox id=togShowPop /></td><TD>'+culang.optionsStatsTabShowPop+'</td></tr>\
            <TR><TD><INPUT type=checkbox id=togincludeMarching /></td><TD>'+culang.optionsStatsTabShowMarches+'</td><TD>&nbsp;</td><TD>&nbsp;</td></tr>\
            <TR><TD><INPUT type=checkbox id=togEnableFormation /></td><TD>'+culang.optionsStatsTabTrainTroops+'</td><TD>&nbsp;</td><TD>&nbsp;</td></tr>\
            <TR><TD><INPUT type=checkbox id=ptEnableFoodWarn /></td><TD colspan=3>'+culang.optionsStatsTabFoodLeft+' <INPUT type=text id=optFoodHours value="'+ Options.foodWarnHours +'" size=3> '+culang.optionsStatsTabFoodLeft2+'</td></tr></table>\
        </div><div id="KsResumeDIV" style="max-height:' + (Options.HauteurBoite-100) +'px;overflow-y:auto"></div>\
        ';
        t.myDiv.innerHTML = str;
        t.KsResumeDIV = ById("KsResumeDIV");
    },
    getContent : function (){
    },

    hide : function (){
        var t = Tabs.Overview;
        clearTimeout (t.displayTimer);
    },
    show : function (){
        var t = Tabs.Overview;
        clearTimeout (t.displayTimer);
        t.setContent();
    },
    setContent : function (){
        var t = Tabs.Overview;
        var rownum = 0;
        var totalentre = 0;
        function UniteFormation(id) {
            var nbunit=0; // 
            for(i=0; i<Cities.numCities; i++) {
                var cityIdd = Cities.cities[i].id;
                var q = Seed.queue_unt['city'+cityIdd];
                var qs = q.toString();
                if (q!=null && q.length>0 ){
                    for (var ii=0; ii<q.length; ii++){
                        if (q[ii][0]==id) nbunit+=parseIntNan(q[ii][1]);

                    }
                }
            }
            totalentre += parseIntNan(nbunit*UniteCout(id));
            return nbunit;
        }
        function UniteCout(id) {
            var Unitcout=parseIntNan(uW.unitupkeeps[id]);
            return Unitcout;
        }

        function _row (name, row, noTotal, typee){
            if (rownum++ % 2)
                style = '';
            else
                style = ' style = "background: #e8e8e8"';
            var tot = 0;
            var m = [];
            m.push ('<TR style="background: #fff" align=right');
            m.push (style);
            m.push ('><TD');
            m.push (style);
            m.push ('><B>');
            m.push (name);
            m.push ('</td>');
            if (noTotal){
                m.push ('<TD');
                m.push (style);
                m.push ('>&nbsp;</td>');
            } else {
                for (i=0; i<row.length; i++)
                    tot += row[i];
                m.push ('<TD style="background: #ffc">');
                if (tot<0) {
                    m.push ("<SPAN class=boldRed>"+UniteKMG(tot)+"</span>");
                } else {
                    if (typee>0 || !Options.EnableReduireUnit)
                        m.push (addCommas(tot));
                    else
                        m.push (UniteKMG(tot));
                }
                m.push ('</td>');
            }
            for (i=0; i<row.length; i++){
                m.push ('<TD');
                m.push (style);
                m.push ('>');
                if (typee>0 || !Options.EnableReduireUnit)
                    m.push (addCommas(row[i]));
                else
                    m.push (UniteKMG(row[i]));
                m.push ('</td>');
            }
            if (Options.EnableFormation && typee>0) {
                m.push ('<td>'+addCommas(UniteFormation(typee))+'</td>');
            }
            if (Options.EnableFormation && name==''+culang.overviewSTrain+'') {
                if (!Options.EnableReduireUnit)
                    m.push("<td>&nbsp;</td><td>" + addCommas(totalentre) + "</td>");
                else
                    m.push("<td>&nbsp;</td><td>" + UniteKMG(totalentre) + "</td>");
            }
            m.push ('</tr>');
            return m.join('');
        }


        try {
            if (Options.includeMarching)
                march = getMarchInfo ();

            dt = new Date ();
            dt.setTime (Seed.player.datejoinUnixTime * 1000);
            allianceId=(typeof(Seed.allianceDiplomacies)=='undefined')?"undefined":Seed.allianceDiplomacies.allianceId;

            str = '<DIV class=pdxStatOverview style="margin-top:4px;">\
            <table width="100%" border="0" cellspacing="0" cellpadding="0" class=pdxTab>\
            <tr>\
            <td class=pdxStatLight><sup><a href="http://kocmon.com/'+getServerId()+'/" target="_blank" title="'+culang.overviewSeverStatsNote+'">' + unsafeWindow.domainName +'</a></sup></td>\
            <td class=pdxStatLight><sup><a href="http://kocmon.com/'+getServerId()+'/search-for-alliance" target="_blank" title="'+culang.overviewAllianceSearchNote+'">'+unsafeWindow.g_js_strings.commonstr.alliance+'</a></sup></td>\
            <td class=pdxStatLight><sup><a href="http://kocmon.com/'+getServerId()+'/highest-might" target="_blank" title="'+culang.overviewMightLeaderboardNote+'">'+unsafeWindow.g_js_strings.commonstr.might+'</a></sup></td>\
            <td><sup>'+unsafeWindow.g_js_strings.commonstr.glory+'</sup></td>\
            <td><sup>'+culang.overviewPlaySince+'</sup></td>\
            <td><sup>'+culang.overviewThrone+'</sup></td>\
            </tr><tr>\
            <td class=pdxStatLight><span ><a href="http://kocmon.com/'+getServerId()+'/players/'+parseInt([Seed.tutorial.userId])+'" target="_blank" title="'+culang.overviewPlayerStatsNote+'"> ' + Seed.player['name'] + '</a> </span></td>\
            <td class=pdxStatLight><span ><a href="http://kocmon.com/'+getServerId()+'/alliances/'+allianceId+'" target="_blank" title="'+culang.overviewAllianceStatsNote+'"> ' + getMyAlliance()[1] +'</a></span></td>\
            <td><span>' + addCommas(Seed.player.might) +'</span></td>\
            <td><span >' + addCommas(Seed.player.glory) +' (' + addCommas(Seed.player.maxGlory) +')</span></td>\
            <td><span >'+ dt.toLocaleDateString() +'</span></td>\
            <TD><SPAN title="'+culang.overviewThroneMightNote+'">'+addCommas(uW.cm.ThroneController.calcMight())+'</span></td></tr>\
            </table></div><span id="debugtest"></span>';
            str += "<DIV id=overMainDiv style='font-size:10px;padding:5px'><TABLE class=pdxTabOverview cellpadding=0 cellspacing=0><TR  align=center><TD width=45 align=center></td><TD width=88 style='background: #ffc; font-size:150%' align=center><SPAN class=shadowCaps>"+culang.mainTotal+"</SPAN></td>";
            for(i=0; i<Cities.numCities; i++) {
                cityID = 'city'+ Cities.cities[i].id;
                Gate = parseInt(Seed.citystats[cityID].gate);
                if(Gate == 0) var couleurr="#77EE77";
                if(Gate != 0) var couleurr="#EE7777";

                str += "<TD width=80 style='background-color:"+couleurr+"'><SPAN class=shadowCaps>"+ Cities.cities[i].name.substring(0,10) +"</SPAN><BR><a href='javascript:void(0)' onclick='cm.utils.CoordinateLinkController.onClick(event)' class='coordinateLink'>("+Cities.cities[i].x +","+ Cities.cities[i].y+")</a><BR>"+ unsafeWindow.provincenames['p'+ Cities.cities[i].provId] +"</td>";
            }

            if (Options.includeMarching)
                str += '<TD width=81><B>'+culang.mainMarches+'</b></td>';
            if (Options.EnableFormation)
                str += "<TD width=81><B>"+culang.overviewSTrain+"</b></td>";

            str += "<td></td></tr>";
            str += "<tr><td><DIV id=pbSwfPlayer></div></td><td></td>";

            for (var cityId in Cities.byID)
                str += '<TD align=center><INPUT type=submit id=ksDefBtn_'+ cityId +' value=""></td>';
            str += '</tr>';
            //Guardians
            str += '<tr><td style="text-align:right;"><img width=20 src="'+IMGWoodGuardian+'"></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
                var ag = Seed.guardian[i];
                var gis = ag.cityGuardianLevels;
                str+='<td style="text-align:center;">';
                if (gis.wood) {
                    if (ag.type == 'wood') var b = 'red';
                        else var b = 'transparent';
                    str += '<img style="border:1px solid '+b+';" title= "'+uW.buildingcost.bdg50[0] + ' Level ' + gis.wood +'" width=20 src="'+IMGWoodGuardian+'">';
                }
                if (gis.ore) {
                    if (ag.type == 'ore') var b = 'red';
                        else var b = 'transparent';
                    str += '<img style="border:1px solid '+b+';" title= "'+uW.buildingcost.bdg51[0] + ' Level ' + gis.ore +'" width=20 src="'+IMGOreGuardian+'">';
                }
                if (gis.food) {
                    if (ag.type == 'food') var b = 'red';
                        else var b = 'transparent';
                    str += '<img style="border:1px solid '+b+';" title= "'+uW.buildingcost.bdg52[0] + ' Level ' + gis.food +'" width=20 src="'+IMGFoodGuardian+'">';
                }
                if (gis.stone) {
                    if (ag.type == 'stone') var b = 'red';
                        else var b = 'transparent';
                    str += '<img style="border:1px solid '+b+';" title= "'+uW.buildingcost.bdg53[0] + ' Level ' + gis.stone +'" width=20 src="'+IMGStoneGuardian+'">';
                }
                str+='</td>';
            }
            str += '</tr>';
            
    // Ascension
            row = [];
            var adata = unsafeWindow.cm.WorldSettings.getSettingAsObject("ASCENSION_REQS_DRUID");    
            for(i=0; i<Cities.numCities; i++) {
                var cityId = Cities.cities[i].id;
                if (Seed.cityData.city[cityId].isPrestigeCity) {
                    var atype = Seed.cityData.city[cityId].prestigeInfo.prestigeType;
                    var alevel = Seed.cityData.city[cityId].prestigeInfo.prestigeLevel;
                    var avalue = Seed.cityData.city[cityId].cityValue;
                    if (adata[parseInt(alevel)+1] != null) {
                        var amin = adata[parseInt(alevel)+1].min;
                        var amax = adata[parseInt(alevel)+1].max;
                        if (avalue < amin) {
                            var aproz = ' (0%)';
                        } else if (avalue >= amax) {
                            var aproz = ' (<b style="color:green;">100%</b>)';
                        } else {
                            var aproz = ' (' + Math.round(1000*(avalue - amin)/(amax - amin))/10 + '%)';
                        }
                    } else {
                        var aproz = '';
                    }
                    
                    if (atype == 1) {
                        row[i] = '<p style="text-align: center; margin:0;"><B>' + culang.mainCityDruid + '<br>Level '+alevel+'</b>'+aproz+'</p>'; //15.10.2012 Bommel
                    } else if (atype == 2) {
                        row[i] = '<p style="text-align: center; margin:0;"><B>' + culang.mainCityFey + '<br>Level '+alevel+'</b>'+aproz+'</p>'; //15.10.2012 Bommel
                    } else {
                        row[i] = '<p style="text-align: center; margin:0;"><B>' + culang.mainCityBriton + '<br>Level '+alevel+'</b>'+aproz+'</p>'; //15.10.2012 Bommel
                    } 
                } else {
                    var avalue = Seed.cityData.city[cityId].cityValue;
                    var amin = adata[1].min;
                    var amax = adata[1].max;
                    if (avalue < amin) {
                        var aproz = '0%';
                    } else if (avalue >= amax) {
                        var aproz = '<b style="color:green;">100%</b>';
                    } else {
                        var aproz = Math.round(1000*(avalue - amin)/(amax - amin))/10 + '%';
                    }
                    row[i] = '<p style="text-align: center; margin:0;">'+aproz+'</p>';                    
                }
            }
            str += _row ('Asc.', row, true, 0);
    
            //Sammelplatz
            row = [];
            for(i=0; i<Cities.numCities; i++) {
                var RInfo = getRallypointInfo(Cities.cities[i].id);
                row[i] = '<SPAN><B>'+ RInfo.usedSlots +'/'+ RInfo.maxMarches +'</b><br>'+RInfo.maxMarchSize+'</span>';
            }
            str += _row ('<img src="'+IMGrallypoint18+'" alt="'+culang.mainSRallyPoint+'" title="'+culang.mainSRallyPoint+'">', row, true, 0);
            
            
            
            rows = [];
            rowsnm = [];
            rows[0] = [];
            // Ressources
            if (Options.showRes) {
                for(i=0; i<Cities.numCities; i++) {
                    cityID = 'city'+ Cities.cities[i].id;
                    rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
                }
                for (r=1; r<6; r++){
                    rows[r] = [];
                    for(i=0; i<Cities.numCities; i++) {
                        cityID = 'city'+ Cities.cities[i].id;
                        if (r==5)
                            rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
                        else
                            rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);

                    }

                }

                if (Options.includeMarching){
                    for (var i=0; i<6; i++)
                        rows[i][Cities.numCities] = parseIntNan(march.resources[i]);
                }
                str += _row ('<img height=18 src="'+IMGgold30+'">', rows[0], false, 0);
                str += _row ('<img height=18 src="'+IMGfood30+'">', rows[1], false, 0);
                str += _row ('<img height=18 src="'+IMGwood30+'">', rows[2], false, 0);
                str += _row ('<img height=18 src="'+IMGstone30+'">', rows[3], false, 0);
                str += _row ('<img height=18 src="'+IMGiron30+'">', rows[4], false, 0);
                str += _row ('<img height=18 src="'+IMGastone30+'">', rows[5], false, 0);

                //Storehouse
                rows = [];
                var STOREHOUSE = [0,100000,200000,300000,400000,500000,600000,700000,800000,900000,1000000,5000000,50000000];
                for(i=0; i<Cities.numCities; i++) {
                    var cityID = 'city'+ Cities.cities[i].id;
                    var sh = getCityBuilding(Cities.cities[i].id,9);
                    if (sh.count == 0) {
                        rows[i] = '0';
                    } else {
                        rows[i] = Math.round(STOREHOUSE[sh.maxLevel] * (1 + Seed.tech.tch14/10 + uW.cm.ThroneController.effectBonus(89)/100));
                    }
                }
                str += _row ('<img title="'+uW.buildingcost.bdg9[0]+'" height=18 src="https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/buildings/storehouse_lvl10_26.png">', rows, true, 0);
                
                if (Options.showProduction) {

                    str += '<TR><TD><BR></td></tr>';

                    row = [];
                    for(i=0; i<Cities.numCities; i++) {
                        var rp = getResourceProduction (Cities.cities[i].id);
                        row[i] = rp[1];
                    }
                    str += _row ('<img height=18 title="'+culang.overviewFoodProduce+'" src="'+IMGfood30+'">', row, false, 0);
                    row = [];
                    for(i=0; i<Cities.numCities; i++) {
                        var rp = getResourceProduction (Cities.cities[i].id);
                        row[i] = rp[2];
                    }
                    str += _row ('<img height=18 title="'+culang.overviewWoodProduce+'" src="'+IMGwood30+'">', row, false, 0);

                    row = [];
                    for(i=0; i<Cities.numCities; i++) {
                        var rp = getResourceProduction (Cities.cities[i].id);
                        row[i] = rp[3];
                    }
                    str += _row ('<img height=18 title="'+culang.overviewStoneProduce+'" src="'+IMGstone30+'">', row, false, 0);

                    row = [];
                    for(i=0; i<Cities.numCities; i++) {
                        var rp = getResourceProduction (Cities.cities[i].id);
                        row[i] = rp[4];
                    }
                    str += _row ('<img height=18 title="'+culang.overviewIronProduce+'" src="'+IMGiron30+'">', row, false, 0);

                }


            }


            var now = unixTime();
            str += '<TR><TD style="font-size:6px"><BR></font></td></tr>';
            str +='<tr style="background: #fff" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/131.jpg title="'+culang.mainBuildTime+'"></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
                var totTime = 0;
                if (Seed.queue_con["city" + Cities.cities[i].id].length > 0) {
                    var q=Seed.queue_con["city" + Cities.cities[i].id][0];
                    var level = q[1];
                    var type = q[0];
                    var title = uW.buildingcost['bdg'+type][0] + ' Lvl. ' + level;  
                    var totTime = 0;
                    totTime = q[4] - now;
                    if (totTime < 0)
                        totTime = 0;
                    if (totTime < 3600)
                        affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                    else
                        affuichage = timestr(totTime);
                    str +='<td><span title="'+title+'">'+ affuichage + "</span></td>";
                } else {
                    str +="<td>0s</td>";
                }
            }
            str +="</tr>";
            //
            str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/1.jpg title="'+culang.mainResearch+'"></b></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
                    str +="<td>";
                var totTime = 0;
                if (Seed.queue_tch["city" + Cities.cities[i].id].length > 0) {
                    var q=Seed.queue_tch["city" + Cities.cities[i].id][0];
                    var level = q[1];
                    var type = q[0];
                    var title = uW.techcost['tch'+type][0] + ' Lvl. ' + level;  
                    var totTime = 0;
                    totTime = q[3] - now;
                    if (totTime < 0)
                        totTime = 0;
                    if (totTime < 3600)
                        affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                    else
                        affuichage = timestr(totTime);

                    str += '<span title="'+title+'">'+ affuichage + '</span>';

                } else {
                    str +="0s";
                }
                //Neue Forschungen
                var totTime = 0;
                if (Seed.queue_tch2["city" + Cities.cities[i].id].length > 0) {
                    var q=Seed.queue_tch2["city" + Cities.cities[i].id][0];
                    var level = q[1];
                    var type = q[0];
                    var title = uW.techcost2['tch'+type][0] + ' Lvl. ' + level;  
                    var totTime = 0;
                    totTime = q[3] - now;
                    if (totTime < 0)
                        totTime = 0;
                    if (totTime < 3600)
                        affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                    else
                        affuichage = timestr(totTime);

                    str += '<br><span title="'+title+'">' + affuichage+ '</span>';

                }                 
                str +="</td>"
            }
            str +="</tr>";
            // crafting
            str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/3.jpg title="'+culang.mainCrafting+'"></b></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
                var totTime = 0;
                if (Seed.queue_craft["city" + Cities.cities[i].id].length > 0) {
                    var q=Seed.queue_craft["city" + Cities.cities[i].id][0];
                    var h = t.craftitems[q.recipeId];
                    var title = uW.itemlist["i"+h].name;
                    var totTime = 0;
                    totTime = q.craftingEtaUnixTime - now;
                    if (totTime < 0)
                        totTime = 0;
                    if (getCityBuilding(Cities.cities[i].id,20).count>0 && totTime == 0)
                        affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                    else
                        affuichage = timestr(totTime);

                    str +="<td><span title='"+title+"'>"+ affuichage + "</span></td>";

                } else {
                    affuichage = timestr(totTime);
                    if (getCityBuilding(Cities.cities[i].id,20).count>0)
                        affuichage = '<span class=boldRed><B>'+ timestr(totTime) +'</b></span>';

                    str +="<td><span>"+affuichage+"</span></td>";
                }
            }
            str +="</tr>";
            // Reviving
            str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src="'+URL_HOSPITAL+'" title="'+culang.overviewHospitalNote+'"></b></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
                str +="<td>";
                var totTime = 0;
                if (Seed.queue_revive["city" + Cities.cities[i].id].length > 0) {
                    var q = Seed.queue_revive["city" + Cities.cities[i].id][0];
                    var unit = q[0];
                    var anz = q[1];
                    var title = addCommas(anz) + ' ' + uW.unitnamedesctranslated['unt'+unit][0];  
                    totTime = q[3] - now;
                    if (totTime < 0)
                        totTime = 0;
                    affuichage = timestr(totTime);
                    str += '<span title="'+title+'">'+ affuichage + '</span>';
                } else {
                    affuichage = timestr(totTime);
                    str +="<span>"+affuichage+"</span>";                
                }

                //2.
                if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity && 
                    uW.cm.BlessingSystemModel.isBlessingActive(uW.cm.BlessingSystemModel.getBlessing().ANCIENT_HEALING, Cities.cities[i].id)) {
                    var totTime = 0;
                    if (Seed.queue_revive2["city" + Cities.cities[i].id].length > 0) {
                        var q = Seed.queue_revive2["city" + Cities.cities[i].id][0];
                        var unit = q[0];
                        var anz = q[1];
                        var title = addCommas(anz) + ' ' + uW.unitnamedesctranslated['unt'+unit][0];  
                        totTime = q[3] - now;
                        if (totTime < 0)
                            totTime = 0;
                        affuichage = timestr(totTime);
                        str += '<br><span title="'+title+'">'+ affuichage + '</span>';
                    } else {
                        affuichage = timestr(totTime);
                        str +="<br><span>"+affuichage+"</span>";
                    }
                }                 
                str +="</td>";
            }
            str +="</tr>";
            
            //Opfer im Fey Altar
            str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src="'+IMGFeyAltar+'" title="'+uW.buildingcost.bdg25[0]+'"></b></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
                str +="<td>";
                if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity) { 
                    if (Seed.cityData.city[Cities.cities[i].id].prestigeInfo.prestigeType == 2) {
                        // 1. Opfer
                        var time = 0;
                        if (Seed.queue_sacr["city" + Cities.cities[i].id].length > 0) {
                            var q = Seed.queue_sacr["city" + Cities.cities[i].id][0];
                            time = q.eta - now;
                            var title = uW.unitnamedesctranslated['unt'+q.unitType][0] + ' +' + parseIntNan((q.multiplier[0] - 1) * 100)+'%';
                            str += '<span title="'+title+'">'+timestr(time)+'</span>';
                        } else {
                            str += timestr(time);
                        }
                        //2. Opfer
                        var time = 0;
                        if (Seed.queue_sacr["city" + Cities.cities[i].id].length > 1) {
                            var q = Seed.queue_sacr["city" + Cities.cities[i].id][1];
                            time = q.eta - now;
                            var title = uW.unitnamedesctranslated['unt'+q.unitType][0] + ' +' + parseIntNan((q.multiplier[0] - 1) * 100)+'%';
                            str += '<br><span title="'+title+'">'+timestr(time)+'</span>';
                        }
                    } else {
                        str +="---";
                    }                    
                } else {
                    str +="---";
                }                
                str +="</td>";
            }
            str +="</tr>";
    
    
            // Population
            if (Options.showPop) {
                str += '<TR><TD style="font-size:6px"><BR></td></tr>';

                for (r=0; r<7; r++){
                    rowsnm[r] = [];
                }
                for(i=0; i<Cities.numCities; i++) {
                    cityID = 'city'+ Cities.cities[i].id;
                    rowsnm[0][i] = parseIntNan(Seed.citystats[cityID]["pop"][1]);
                    rowsnm[1][i] = parseIntNan(Seed.citystats[cityID]["pop"][0]);
                    rowsnm[2][i] = parseIntNan(Seed.citystats[cityID]["pop"][3]);
                    rowsnm[5][i] = parseIntNan(Seed.citystats[cityID]["pop"][2]);
                    if (rowsnm[5][i] < 100)
                        rowsnm[5][i] = '<SPAN class=boldRed>' + rowsnm[5][i] + '</SPAN>';
                    rowsnm[3][i] = rowsnm[0][i] * rowsnm[5][i] / 100 - rowsnm[2][i];
                    rowsnm[4][i] = rowsnm[1][i] - rowsnm[2][i];
                    rowsnm[6][i] = parseIntNan(Seed.citystats[cityID]["gold"][1]);
                    if (rowsnm[6][i] > 0)
                        rowsnm[6][i] = '<SPAN class=boldRed>' + rowsnm[6][i] + '</SPAN>';
                }

                rownum = 0;
                str += _row (''+culang.overviewMaxPop+'',  rowsnm[0]);
                str += _row (''+culang.overviewSPop+'',  rowsnm[1]);
                str += _row (''+culang.mainWorker+'',  rowsnm[2]);
                str += _row (''+culang.mainMaxIdle+'', rowsnm[3]);
                str += _row (''+culang.mainIdle+'', rowsnm[4]);
                str += _row ('<img height=20 src="'+IMGhappiness+'" title="'+culang.mainLuck+'">',  rowsnm[5], true);
                str += _row ('<img height=20 src="'+IMGtaxes+'" title="'+culang.mainTax+'">', rowsnm[6], true);
            }

            str += '<TR><TD style="font-size:6px"><BR></td></tr>';
            row = [];
            var totalbouffe = 0;
            var MaxUpkeep = uW.cm.thronestats.boosts.Upkeep.Max;
            var TR = Math.min(uW.cm.ThroneController.effectBonus(79), MaxUpkeep) / 100;
        
            for(i=0; i<Cities.numCities; i++) {
                var rp = getResourceProduction (Cities.cities[i].id);
                var usage = parseIntNan(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
                usage = Math.floor(usage - (usage * TR));
                row[i] = rp[1] - usage;
            }
            str += _row ('<img src="'+IMGfoodplusminus20+'" alt="'+culang.overviewSProduce+'" title="'+culang.overviewSProduce+'">', row, false,  0);

            for(i=0; i<Cities.numCities; i++) {
                if (row[i] >= 0)
                    row[i] = '----';
                else {
                    var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-row[i]) * 3600;
                    if (timeLeft > 86313600)
                        row[i] = '----';
                    else {
                        if (Options.enableFoodWarn && timeLeft<(Options.foodWarnHours*3600))
                            row[i] = '<SPAN class=whiteOnRed><blink>'+ timestrShort(timeLeft) +'</blink></span>';
                        else
                            row[i] = timestrShort(timeLeft);
                    }
                }
            }
            str += _row ('<img src="'+IMGfoodleft20+'" alt="'+culang.overviewFoodLeft+'" title="'+culang.overviewFoodLeft+'">', row, true, 0);

            if (Options.showTroops) {

                str += '<TR><TD style="font-size:6px"><BR></td></tr>';
                for (r=1; r<16; r++){
                    rows[r] = [];
                    for(i=0; i<Cities.numCities; i++) {
                        cityID = 'city'+ Cities.cities[i].id;
                        rows[r][i] = parseIntNan(Seed.units[cityID]['unt'+r]);
                    }
                }
                if (Options.includeMarching){
                    for (var i=0; i<16; i++)
                        // rows[i][Cities.numCities] = march.marchUnits[i];
                        rows[i][Cities.numCities] = parseIntNan(march.marchUnits[i]);
                }
                rownum = 0;
                this.totalentre = 0;
                for (r=1; r<16; r++){
                    str += _row ('<img height=18 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg>', rows[r],false, r);
                }
                str += '<TR><TD style="font-size:6px"><BR></font></td></tr>';
            }
            //Ausbildung #1
            str +='<tr style="background: #e8e8e8" align=right><td><img src="'+IMGtrain20+'" alt="'+culang.overviewSTrain+'" title="'+culang.overviewSTrain+'"></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
                str += "<td>";
                var totTime = 0;
                var q = Seed.queue_unt['city'+Cities.cities[i].id];
                var max = 0;
                var title = '';
                if (q!=null && q.length>0) {
                    for (var j = 0; j < q.length; j++) {
                        if (!q[j][7]) {
                            var unit = q[j][0];
                            var anz = q[j][1];
                            var qmax = parseInt(q[j][3]);
                            var time = qmax - parseInt(q[j][2]);
                            if (parseInt(q[j][2]) < now) var time = parseInt(q[j][3]) - now;
                            if (qmax > now) 
                                title += addCommas(anz) + ' ' + uW.unitnamedesctranslated['unt'+unit][0] +' (' + timestr(time) +")\n";  
                            if (qmax > max ) max = qmax;
                        }
                    }
                    totTime = max - now;
                    if (totTime < 0) totTime = 0;
                }
                if (totTime < 86400)
                    str += '<SPAN title="'+title+'" class="boldRed"><B>'+ timestr(totTime) +'</b></span>';
                else
                    str += '<SPAN title="'+title+'">'+timestr(totTime) + '</span>';
                //2.
                var totTime = 0;
                var q = Seed.queue_unt['city'+Cities.cities[i].id];
                var max = 0;
                var title = '';
                if (q!=null && q.length>0) {
                    for (var j = 0; j < q.length; j++) {
                        if (q[j][7]) {
                            var unit = q[j][0];
                            var anz = q[j][1];
                            var qmax = parseInt(q[j][3]);
                            var time = qmax - parseInt(q[j][2]);
                            if (parseInt(q[j][2]) < now) var time = parseInt(q[j][3]) - now;
                            if (qmax > now) 
                                title += addCommas(anz) + ' ' + uW.unitnamedesctranslated['unt'+unit][0] +' (' + timestr(time) +")\n";  
                            if (qmax > max ) max = qmax;
                        }
                    }
                    totTime = max - now;
                    if (totTime < 0) totTime = 0;
                }
                if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity) {
                    if (totTime < 86400)
                        str += '<br><SPAN title="'+title+'" class="boldRed"><B>'+ timestr(totTime) +'</b></span>';
                    else
                        str += '<br><SPAN title="'+title+'">'+timestr(totTime) + '</span>';
                }
                
                str += "</td>";
            }
                    
            // Defenses du remparts
            if (Options.showDefense) {
                str += '<TR><TD style="font-size:6px"><BR></td></tr>';
                owsnm = [];
                for (r=0; r<5; r++){
                    rowsnm[r] = [];
                }
                for(i=0; i<Cities.numCities; i++) {
                    var wall = {};
                    getWallInfo (Cities.cities[i].id, wall);
                    rowsnm[0][i] = parseIntNan(wall.Crossbows);
                    rowsnm[1][i] = parseIntNan(wall.Trebuchet);
                    rowsnm[2][i] = parseIntNan(wall.Caltrops);
                    if (isNaN(parseInt(wall.SpikedBarrier))) // KoC bug if wall lvl 0
                        rowsnm[3][i] = 0;
                    else
                        rowsnm[3][i] = parseIntNan(wall.SpikedBarrier);
                    rowsnm[4][i] = parseIntNan(wall.Trap);
                }
                if (Options.defBau){
                    var q = Seed.queue_unt;
                    for(i=0; i<Cities.numCities; i++) {
                        var q = Seed.queue_fort['city'+Cities.cities[i].id];
                        if (q && q.length>0){
                            for (qi=0; qi<q.length; qi++) {
                                if (q[qi][0]==53)
                                    rowsnm[0][i] += parseIntNan(q[qi][1]);
                                if (q[qi][0]==55)
                                    rowsnm[1][i] += parseIntNan(q[qi][1]);
                                if (q[qi][0]==60)
                                    rowsnm[4][i] += parseIntNan(q[qi][1]);
                                if (q[qi][0]==61)
                                    rowsnm[2][i] += parseIntNan(q[qi][1]);
                                if (q[qi][0]==62)
                                    rowsnm[3][i] += parseIntNan(q[qi][1]);
                            }
                        }
                    }
                }

                rownum = 0;
                str += _row ('<img height=18 title="'+unsafeWindow.fortcost.frt53[0]+'" src="'+IMGmiddleCrossbows+'">',  rowsnm[0]);
                str += _row ('<img height=18 title="'+unsafeWindow.fortcost.frt55[0]+'" src="'+IMGmiddleTrebuchet+'">',  rowsnm[1]);
                str += _row ('<img height=18 title="'+unsafeWindow.fortcost.frt60[0]+'" src="'+IMGmiddleTrap+'">',  rowsnm[4]);
                str += _row ('<img height=18 title="'+unsafeWindow.fortcost.frt61[0]+'" src="'+IMGmiddleCaltr+'">', rowsnm[2]);
                str += _row ('<img height=18 title="'+unsafeWindow.fortcost.frt62[0]+'" src="'+IMGmiddleSpiked+'">',  rowsnm[3]);
            }

            
            str +='<tr style="background: #e8e8e8" align=right><td><img src="'+IMGwalltrain20+'" alt="'+culang.mainSDefense+'" title="'+culang.mainSDefense+'"></td><td>&nbsp;</td>';
            for(i=0; i<Cities.numCities; i++) {
                str += "<td>";
                var wall = {};
                getWallInfo (Cities.cities[i].id, wall);
                var totTime = 0;
                var q = Seed.queue_fort['city'+Cities.cities[i].id];
                var max = 0;
                var title = '';
                if (q!=null && q.length>0) {
                    for (var j = 0; j < q.length; j++) {
                        var unit = q[j][0];
                        var anz = q[j][1];
                        var qmax = parseInt(q[j][3]);
                        if (qmax > now)
                            title += addCommas(anz) + ' ' + uW.fortcost['frt'+unit][0] + "\n";  
                        if (qmax > max ) max = qmax;
                    }
                    totTime = max - now;
                    if (totTime < 0) totTime = 0;
                }
                if (totTime<1 && (wall.wallSpaceUsed < wall.wallSpace-4 || wall.fieldSpaceUsed < wall.fieldSpace-4))
                    str += '<SPAN title="'+title+'" class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                else
                    str += '<SPAN title="'+title+'">'+ timestr(totTime) +'</span>';
                    
                str += "</td>";
            }

            str += '<TR><TD style="font-size:6px"><BR></td></tr>';


            // Terres sauvages
            row = [];
            for(i=0; i<Cities.numCities; i++) {
                var totWilds = 0;
                dat = Seed.wilderness['city'+ Cities.cities[i].id];
                if (dat!=null && matTypeof(dat)=='object')
                    for (k in dat)
                        ++totWilds;
                var nivcastle = parseInt(Seed.buildings['city'+ Cities.cities[i].id].pos0[1]);
                var castle = nivcastle;
                if (nivcastle==11) castle=12;
                if (nivcastle==12) castle=14;
                if (totWilds < castle)
                {
                    row[i] = '<SPAN class=boldRed><B>'+ totWilds +'/'+ castle +'</b></span>';
                }else{

                    row[i] = totWilds +'/'+ castle;
                }
            }
            str += _row ('<img src="'+IMGwild20+'" alt="'+culang.mainSWild+'" title="'+culang.mainSWild+'">', row, true, 0);
            row = [];
            var did = {};
            for(i=0; i<Cities.numCities; i++) {
                totKnights = 0;
                dat = Seed.knights['city'+ Cities.cities[i].id];
                for (k in dat)
                    ++totKnights;

                var Knidispo = 0;
                var niveauPointRall=parseInt(getCityBuilding (Cities.cities[i].id, 12).maxLevel);
                var add = 0;
                if (Seed.cityData.city[Cities.cities[i].id].isPrestigeCity) add = 3;
                if (niveauPointRall==12) niveauPointRall=11;  // fix : Send eleven armies at a time for level 12
                niveauPointRall = niveauPointRall + add;
                for (var iKR=0; iKR<knightRoles.length; iKR++){
                    var leader = Seed.leaders['city'+Cities.cities[i].id][knightRoles[iKR][1]+'KnightId'];
                    if (leader == 0) {

                    }else{
                        did['knt'+leader] = true;
                    }
                }
                for (k in Seed.knights['city'+Cities.cities[i].id]){
                    if (!did[k])
                        Knidispo++;
                }
                if (Knidispo<niveauPointRall) {
                    row[i] = '<b>' + totKnights + '</b> - <span title="'+culang.overviewKnightsCheck+'"><SPAN class=boldRed><B>'+Knidispo+'/' + niveauPointRall +'</span></span>';
                }else {
                    row[i] = '<b>' + totKnights + '</b> - <span title="'+culang.overviewKnightsCheck+'">'+Knidispo+'/' + niveauPointRall +'</span>';
                }

            }
            str += _row ('<img src="'+IMGknights20+'" alt="'+culang.mainKnights+'" title="'+culang.mainKnights+'">', row, true, 0);
            str += "</table>";
            str += "<br><input id='ptButDebug' type='submit' name='SEED' value='DEBUG'>";
            //str += "<br><pre>"+inspect(uW.cm.thronestats.boosts,3) + "</pre>";
            t.KsResumeDIV.innerHTML = str +'</div>';

            document.getElementById('ptButDebug').addEventListener('click', function (){debugWin.doit()}, false);    
            
            
            function addListener (but, i){
                but.addEventListener ('click', function (){t.butToggleDefMode(i)}, false);
            }
            for (var cityId in Cities.byID){
                var but = document.getElementById ('ksDefBtn_'+ cityId);
                addListener (but, cityId);
                t.defMode[cityId] =  parseInt(Seed.citystats["city" + cityId].gate);
                t.displayDefMode (cityId);
            }

            Tabs.Options.togOpt ('ptEnableReduireUnit', 'EnableReduireUnit');
            Tabs.Options.togOpt ('togEnableFormation', 'EnableFormation');
            Tabs.Options.togOpt ('togShowDefense', 'showDefense');
            Tabs.Options.togOpt ('togShowProduction', 'showProduction');
            Tabs.Options.togOpt ('togincludeMarching', 'includeMarching');
            Tabs.Options.togOpt ('togShowTroops', 'showTroops');
            Tabs.Options.togOpt ('togShowPop', 'showPop');
            Tabs.Options.togOpt ('togShowRes', 'showRes');

            ById('optFoodHours').addEventListener ('change', function () {
                var x = ById('optFoodHours').value;
                if (isNaN(x) || x<0.01 || x>99999){
                    ById('optFoodHours').value = Options.foodWarnHours;
                    return;
                }
                Options.foodWarnHours = x;
                saveOptions();
            }, false);

        } catch (ex){
            t.KsResumeDIV.innerHTML = '<PRE>'+ ex.name +': '+ ex.message + " @"+ ex.lineNumber +'</pre>';
            GM_log(dump(ex,"ex",1));
        }
        t.displayTimer = setTimeout (t.setContent, 30000);
    },
    butToggleDefMode : function (cityId){
        var t = Tabs.Overview;
        var mode = 1;
        if (Seed.citystats["city" + cityId].gate != 0)
            mode = 0;
        t.ajaxSetDefMode (cityId, mode, function (newMode){
            t.defMode[cityId] = newMode;
            t.displayDefMode (cityId);
        });
    },

    displayDefMode : function (cityId){
        var t = Tabs.Overview;
        var but = ById('ksDefBtn_'+ cityId);
        if (t.defMode[cityId]){
            but.className = 'defButtonOn';
            but.value = ''+culang.mainHDef+' = '+culang.buttonON;
        } else {
            but.className = 'defButtonOff';
            but.value = ''+culang.mainHDef+' = '+culang.buttonOFF;
        }
    },
    ajaxSetDefMode : function (cityId, state, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = cityId;
        params.state = state;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/gate.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {
                    Seed.citystats["city" + cityId].gate = state;
                    notify (state);
                }
            },
            onFailure: function () {
            }
        })
    },
};
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Reports.js">
/************************************************************************************
 *                        KOC POWER - TABS REPORTS                                    *
 ************************************************************************************/
Tabs.Rpt = { //TODO rename to Reports
    tabOrder:        TabOptions.toReports,
    tabLabel:        culang.mainReports,
    cont:            null,
    state:            null,
    minPages:        parseInt(Options.arPageFrom),
    maxPages:        parseInt(Options.arPageTo),
    data:            [],
    dataDF:    [],dataAT:    [],
    report:            [],
    reportDF:        [],
    reportAT:        [],
    totalPages:    parseInt(Options.arPageTo),
    what:            '',
    whatNot:        '',
    content:        '',
    timer:null,

    show : function () {
        var t = Tabs.Rpt;
        if (Options.RptAuto) t.handleRptSearch();
    },
    hide : function (){
    },

    init : function (div) {
        var t = Tabs.Rpt;
        t.cont = div;
        unsafeWindow.getmsg = t.getMailBody;
        unsafeWindow.DelMail = t.DeleteMail;
        unsafeWindow.getReport = t.getReportBody;
        unsafeWindow.getReportAC = t.getReportBodyAC;
        unsafeWindow.DelReport = t.DeleteReport;
        if (!Options.reportScanner.pause) Options.reportScanner.pause = 2;    
        var tc = '<DIV class=pdxStat>'+culang.reportsHead+' - <input type=button value="?" id=boaiderapport class=buttonHelp></DIV><DIV class=pdxEntry><TABLE><TR align=center valign=center>';
        tc += '<TD class=xtab style="line-height:30px;" align=right>'+culang.mainType+':&nbsp;<SELECT id="idRptType">';
        tc += '<OPTION value="alliance" ' + (Options.rptType=='alliance'?'SELECTED':'') + '>'+culang.reportAllianceReports+'</OPTION>';
        tc += '<OPTION value="player" ' + (Options.rptType=='player'?'SELECTED':'') + '>'+culang.reportPlayerReports+'</OPTION>';
        tc += '<OPTION value="inbox" ' + (Options.rptType=='inbox'?'SELECTED':'') + '>'+culang.reportInbox+'</OPTION>';
        tc += '<OPTION value="outbox" ' + (Options.rptType=='outbox'?'SELECTED':'') + '>'+culang.reportOutbox+'</OPTION></SELECT>';
        tc += '<BR /><INPUT id=idRptSearch type=submit value="'+culang.mainOK+'" />&nbsp;'+culang.reportAutoSearch+': <input type=checkbox id="idRptAuto" ' +(Options.RptAuto?'CHECKED':'')+'> '+culang.mainPage+':&nbsp;<INPUT id="idRptPageFrom" size=1 value="' + Options.arPageFrom + '">&#8211;<INPUT id="idRptPageTo" size=1 value="' + Options.arPageTo + '"></TD>';
        tc += '<TD class=xtab style="line-height:30px;" align=right>'+culang.mainAttacker+': &nbsp;<SELECT id="idRptAttacker">'; // Options.arPageFrom - Options.arPageTo
        tc += '<OPTION value="Them" ' + (Options.arAttacker=='Them'?'SELECTED':'') + '>'+culang.reportThemAttacker+'</OPTION>';
        tc += '<OPTION value="Us" ' + (Options.arAttacker=='Us'?'SELECTED':'') + '>'+culang.reportUsAttacker+'</OPTION>';
        tc += '<OPTION value="Both" ' + (Options.arAttacker=='Both'?'SELECTED':'') + '>'+culang.reportBothAttacker+'</OPTION></SELECT>';
        tc += '<BR />'+culang.mainTarget+':&nbsp;<SELECT id="idRptTarget">';
        tc += '<OPTION value="Them" ' + (Options.arTarget=='Them'?'SELECTED':'') + '>'+culang.reportThemTarget+'</OPTION>';
        tc += '<OPTION value="Us" ' + (Options.arTarget=='Us'?'SELECTED':'') + '>'+culang.reportUsTarget+'</OPTION>';
        tc += '<OPTION value="Both" ' + (Options.arTarget=='Both'?'SELECTED':'') + '>'+culang.reportBothTarget+'</OPTION></SELECT></TD>';
        tc += '<TD class=xtab style="line-height:30px;" align=right>'+culang.reportContain+':&nbsp;<INPUT id=idRptWhat type=text size=11 maxlength=50 value=""><BR />';
        tc += ''+culang.reportDifferent+':&nbsp;<INPUT id=idRptWhatNot type=text size=11 maxlength=50 value=""></TD>';
        tc += '<TD class=xtab style="line-height:30px;" align=left><INPUT id=idRptAttack type=checkbox '+(Options.arAttack?'CHECKED':'')+' />&nbsp;'+culang.mainAttack+'<BR />';
        tc += '<INPUT id=idRptScout type=checkbox '+(Options.arScout?'CHECKED':'')+' />&nbsp;'+culang.mainScout+'</TD>';
        tc += '<TD class=xtab style="line-height:30px;" align=left><INPUT id=idRptReinforce type=checkbox '+(Options.arReinforce?'CHECKED':'')+' />&nbsp;'+culang.mainReinforce+'<BR />';
        tc += '<INPUT id=idRptTransport type=checkbox '+(Options.arTransport?'CHECKED':'')+' />&nbsp;'+culang.mainTransport+'</TD>';
        tc += '<TD style="border-right:1px solid black;line-height:30px;" class=xtab align=left><select id=idRptFiltre1><option value="">--</option><option value="0">'+culang.mainWild+'</option><option value=54>'+culang.dfShort+'</option></select><br>'+culang.reportSynthesis+' <input type=checkbox id=KsSyntheseAttack></TD>';
        tc += '<TD class=xtab align=center style="line-height:30px;"><input id=reportScannerStart type=submit value="';
        if (Options.reportScanner.start) {
            tc += culang.reportScannerStartOn; //23.10.2012 Bommel
            Options.reportScanner.start = true;
        } else {
            tc += culang.reportScannerStartOff; //23.10.2012 Bommel
            Options.reportScanner.start = false;
        }
        tc += '"><br><INPUT id=reportScannerPause size="1" maxlength="3" type=text style="text-align:center;" value="'+Options.reportScanner.pause+'"> Min.</td>';
        tc += '</TR></TABLE></DIV>';
        tc += '<DIV class=pdxStat><TABLE width=100% cellspacing=0><TR><TD class=xtab align=left width=125><DIV id=idRptSearched></DIV></TD></TD>';
        tc += '<TD class=xtab><TD class=xtab align=center><SPAN style="white-space:normal" id=idRptStatus>&nbsp;</span></TD></TD>';
        tc += '<TD class=xtab><TD class=xtab align=right width=125><DIV id=idRptFound></DIV></TD></TR></TABLE></DIV>';
        tc += '<DIV id="idBoRptResultsDiv" style="max-height:' + (Options.HauteurBoite-140) +'px; overflow:auto; white-space:nowrap;"></DIV>';
        t.cont.innerHTML = tc;
        //ReportScanner
        ById('reportScannerStart').addEventListener('click', function(){t.RSStart();} , false);
        ById('reportScannerPause').addEventListener('change', function(){
            var value = parseIntNan(ById('reportScannerPause').value);
            if (value < 2) value = 2;
            Options.reportScanner.pause = value;
            saveOptions();
            ById('reportScannerPause').value = value;
            if (t.timer != null) {
                clearTimeout (t.timer);
                t.timer = setTimeout(t.RSTimer, Options.reportScanner.pause * 60000);                
            }
        } , false);
        
        ById('boaiderapport').addEventListener('click', function(){
            window.open(homePage+" ");
        } , false);

        ById('idRptType').addEventListener ('change', t.handleRptType, false);
        ById('idRptPageFrom').addEventListener ('change', t.handleRptPages, false);
        ById('idRptPageTo').addEventListener ('change', t.handleRptPages, false);
        ById('idRptAttacker').addEventListener ('change', t.handleRptAttacker, false);
        ById('idRptTarget').addEventListener ('change', t.handleRptTarget, false);
        ById('idRptWhat').addEventListener ('keyup', t.handleRptWhat, false);
        ById('idRptWhatNot').addEventListener ('keyup', t.handleRptWhatNot, false);
        ById('idRptSearch').addEventListener ('click', t.handleRptSearch, false);
        ById('idRptFiltre1').addEventListener ('change', t.handleRptWhat, false);

        t.togOpt ('idRptAttack', 'arAttack');
        t.togOpt ('idRptScout', 'arScout');
        t.togOpt ('idRptReinforce', 'arReinforce');
        t.togOpt ('idRptTransport', 'arTransport');
        t.togOpt ('idRptAuto','RptAuto');

    },
    RSStart: function() {
        var t = Tabs.Rpt;
        if (Options.reportScanner.start) {
            ById("reportScannerStart").value = culang.reportScannerStartOff; //23.10.2012 Bommel
            Options.reportScanner.start = false;
            ById("idRptType").disabled = false;
            clearTimeout (t.timer);
        } else {
            ById("reportScannerStart").value = culang.reportScannerStartOn; //23.10.2012 Bommel
            Options.reportScanner.start = true;
            ById("idRptType").value = "alliance";
            ById("idRptType").disabled = true;
            t.handleRptType();
            t.RSTimer();
        }
        saveOptions();
    },
    RSTimer : function() {
        var t = Tabs.Rpt;
        clearTimeout(t.timer);
    t.timer = setTimeout(t.RSTimer, Options.reportScanner.pause * 60000);
        t.handleRptSearch();
  },
    AutoStart: function() {
        var t = Tabs.Rpt;
        if (Options.reportScanner.start) {
            t.timer = setTimeout(t.RSTimer, 15000);
            ById("idRptType").value = "alliance";
            ById("idRptType").disabled = true;
            t.handleRptType();
        }
    },
    DeleteMail: function(rptid, type) {
        var t = Tabs.Rpt;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.requestType="ACTION_ON_MESSAGES";
        params.selectedAction="delete";
        params.boxType=ById('idRptType').value;
        params.selectedMessageIds=rptid;

        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {
                    t.handleRptSearch();
                }
                if (notify) //TODO Fehler: notify is not defined
                    notify (rslt.errorMsg);
            },
            onFailure: function () {
                if (notify)
                    notify ('AJAX ERROR');
            },
        });
    },

    DeleteReport: function(rptid, isUnread) {
        var t = Tabs.Rpt;

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.s0rids = rptid;
        params.s1rids = '';
        params.cityrids = '';

        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {

                    if (isUnread){
                        unsafeWindow.seed.newReportCount = parseInt(unsafeWindow.seed.newReportCount) - 1;
                        unsafeWindow.messages_notify_bug()
                    }
                    //t.handleRptSearch();
                    //t.DisplayRpt();
                }

            },
            onFailure: function () {
                t.handleRptSearch();
            },
        });
    },
    togOpt: function (checkboxId, optionName){
        var t = Tabs.Rpt;
        var checkbox = ById(checkboxId);
        checkbox.addEventListener ('change', eventHandler, false);
        function eventHandler (){
            Options[optionName] = this.checked;
            saveOptions();
            if (t.data.length > 0)
                if (Options.rptType == 'alliance' || Options.rptType == 'player')
                    t.DisplayRpt();
                else
                    t.DisplayMail();
        }
    },

    handleRptType: function(){
        var t = Tabs.Rpt;
        Options.rptType = ById("idRptType").value;
        saveOptions();
        ById("idRptSearched").innerHTML = '';
        ById("idRptStatus").innerHTML = '&nbsp;';
        ById("idRptFound").innerHTML = '';
        ById("idBoRptResultsDiv").innerHTML = '';
    },

    handleRptPages: function(){
        var t = Tabs.Rpt;
        t.minPages=parseInt(ById("idRptPageFrom").value);
        t.maxPages=parseInt(ById("idRptPageTo").value);
        if (t.maxPages < t.minPages) {
            t.maxPages = t.minPages;
            ById("idRptPageTo").value = t.maxPages;
        }
        Options.arPageFrom = t.minPages;
        Options.arPageTo = t.maxPages;
        saveOptions();
        t.totalPages=t.maxPages;
    },

    handleRptAttacker: function(){
        var t = Tabs.Rpt;
        Options.arAttacker = ById("idRptAttacker").value;
        saveOptions();
        if ((Options.rptType == 'alliance' || Options.rptType == 'player') && t.data.length > 0)
            t.DisplayRpt();
    },

    handleRptTarget: function(){
        var t = Tabs.Rpt;
        Options.arTarget = ById("idRptTarget").value;
        saveOptions();
        if ((Options.rptType == 'alliance' || Options.rptType == 'player') && t.data.length > 0)
            t.DisplayRpt();
    },

    handleRptWhat: function(){
        var t = Tabs.Rpt;
        t.what = ById("idRptWhat").value;
        if (t.data.length > 0)
            if (Options.rptType == 'alliance' || Options.rptType == 'player')
                t.DisplayRpt();
            else
                t.DisplayMail();
    },

    handleRptWhatNot: function(){
        var t = Tabs.Rpt;
        t.whatNot = ById("idRptWhatNot").value;
        if (t.data.length > 0)
            if (Options.rptType == 'alliance' || Options.rptType == 'player')
                t.DisplayRpt();
            else
                t.DisplayMail();
    },

    handleRptSearch: function(){
        var t = Tabs.Rpt;
        if (t.searchRunning){
            t.searchRunning = false;
            t.stopSearch (culang.mainCancel);
            return;
        }
        t.handleRptPages();
        document.getElementById ('idRptSearch').value = ''+culang.mainStop+'';
        ById('idRptStatus').innerHTML = culang.reportSearchedPages+' ' + t.minPages + ' / ' + t.maxPages;
        t.searchRunning = true;
        t.data=[];
        t.report = [];
        t.dataDF=[];
        t.dataAT=[];
        t.reportAT=[];
        t.reportDF = [];
        if (Options.rptType == 'alliance' || Options.rptType == 'player')
            t.getRpt(t.minPages);
        else
            t.getMail(t.minPages);
    },

    stopSearch: function (msg){
        var t = Tabs.Rpt;
        if (t.searchRunning || msg == culang.mainCancel)
            document.getElementById ('idRptStatus').innerHTML = '<FONT color=#ffaaaa>' + msg + '</FONT>';
        document.getElementById ('idRptSearch').value = ''+culang.mainOK+'';
        t.searchRunning = false;
        if (Options.rptType == 'alliance' || Options.rptType == 'player')
            t.DisplayRpt();
        else
            t.DisplayMail();
    },

    getMail: function (pageNum){
        var t = Tabs.Rpt;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.pf=0;
        params.requestType="GET_MESSAGE_HEADERS_FOR_USER_INBOX";
        params.boxType = ById('idRptType').value;
        params.pageNo = pageNum;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                t.getMailCallback(rslt, pageNum);
            },
            onFailure: function () {
            },
        }, false);
    },

    getMailCallback: function(rslt, page) {
        var t = Tabs.Rpt;
        if (rslt) {
            if (!rslt.ok) {
                ById("idRptStatus").innerHTML = '<FONT color=#ffaaaa>' + rslt.errorMsg + '</FONT>';
                return;
            }
            t.totalPages=parseInt(rslt.noOfPages);
            if (t.totalPages < t.maxPages)
                t.maxPages = t.totalPages;
            if (rslt.message && page) {
                var ml = rslt.message;
                if (rslt.messageCount > 0) {
                    var rptkeys = unsafeWindow.Object.keys(ml);
                    for (var i = 0; i < rptkeys.length; i++) {
                        var rpt = ml[rptkeys[i]];
                        rpt.page = page;
                        t.data.push(rpt);
                    }
                }
            }
            if (parseInt(page)+1 <= t.maxPages && t.searchRunning) {
                ById("idRptStatus").innerHTML = culang.reportSearchedPages+' ' + (parseInt(page)+1) + ' / ' + t.maxPages;
                t.getMail(parseInt(page)+1);
                if (t.data.length > 0)
                    t.DisplayMail();
            } else if (page)
                t.stopSearch (''+culang.mainHDone+'');
        }
    },

    getRpt: function (pageNum){
        var t = Tabs.Rpt;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.pageNo = pageNum;
        if (Options.rptType == 'alliance')
            params.group = "a";
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt){
                t.getRptCallback (rslt, pageNum);
            },
            onFailure: function (rslt){
                t.getRptCallback (rslt, pageNum);
            },
        }, false);
    },
    getRptCallback: function(rslt, page){
        var t = Tabs.Rpt;
        if (rslt) {
            if (!rslt.ok) {
                ById("idRptStatus").innerHTML = '<FONT color=#ffaaaa>' + rslt.errorMsg + '</FONT>';
                return;
            }
            t.totalPages=parseInt(rslt.totalPages);
            if (t.totalPages < t.maxPages)
                t.maxPages = t.totalPages;
            if (rslt.arReports && page) {
                var ar = rslt.arReports;
                //if (ar.length == 0)
                //t.stopSearch('Page vide trouve depuis la page ' + page + ' - Kabam glitch');
                var rptkeys = unsafeWindow.Object.keys(ar);
                for (var i = 0; i < rptkeys.length; i++) {
                    var rpt = ar[rptkeys[i]];
                    var reportId = parseInt(rpt.reportId);
                    t.report[reportId] = [];
                    t.report[reportId].side1Name = rslt.arPlayerNames['p'+rpt.side1PlayerId];
                    t.report[reportId].side1AllianceId = parseInt(rpt.side1AllianceId);
                    if (rpt.side1AllianceId > 0)
                        t.report[reportId].side1AllianceName = rslt.arAllianceNames['a'+rpt.side1AllianceId];
                    else
                        t.report[reportId].side1AllianceName = '-';
                    if (rpt.side1CityId > 0)
                        t.report[reportId].side1CityName = rslt.arCityNames['c'+rpt.side1CityId];
                    else
                        t.report[reportId].side1CityName = '-';
                    t.report[reportId].side1XCoord = rpt.side1XCoord;
                    t.report[reportId].side1YCoord = rpt.side1YCoord;
                    if (parseInt(rpt.side0PlayerId) == 0) { // Kabam
                        t.report[reportId].side0Name = ''+culang.reportEnemy+'';
                        t.report[reportId].side0AllianceName = '';
                        t.report[reportId].side0CityName = '';
                    } else {
                        t.report[reportId].side0Name = rslt.arPlayerNames['p'+rpt.side0PlayerId];
                        if (rpt.side0AllianceId > 0)
                            t.report[reportId].side0AllianceName = rslt.arAllianceNames['a'+rpt.side0AllianceId];
                        else
                            t.report[reportId].side0AllianceName = '-';
                        if (rpt.side0CityId > 0)
                            t.report[reportId].side0CityName = rslt.arCityNames['c'+rpt.side0CityId];
                        else
                            t.report[reportId].side0CityName = '-';
                    }
                    t.report[reportId].side0AllianceId = parseInt(rpt.side0AllianceId);
                    t.report[reportId].side0XCoord = rpt.side0XCoord;
                    t.report[reportId].side0YCoord = rpt.side0YCoord;
                    if (parseInt(rpt.side0TileType) == 10)
                        t.report[reportId].side0TileTypeText=culang.kocGrassland;
                    else if (parseInt(rpt.side0TileType) == 11)
                        t.report[reportId].side0TileTypeText=culang.kocLake;
                    else if (parseInt(rpt.side0TileType) == 20)
                        t.report[reportId].side0TileTypeText=culang.kocForests;
                    else if (parseInt(rpt.side0TileType) == 30)
                        t.report[reportId].side0TileTypeText=culang.kocHill;
                    else if (parseInt(rpt.side0TileType) == 40)
                        t.report[reportId].side0TileTypeText=culang.kocMount;
                    else if (parseInt(rpt.side0TileType) == 50)
                        t.report[reportId].side0TileTypeText=culang.kocPlain;
                    else if (parseInt(rpt.side0TileType) == 51 && parseInt(rpt.side0CityId) == 0)
                        t.report[reportId].side0TileTypeText=culang.mainCity;
                    else if (parseInt(rpt.side0TileType) == 54)
                        t.report[reportId].side0TileTypeText=culang.shortDarkForest;
                    else if (parseInt(rpt.side0CityId) == 0)
                        t.report[reportId].side0TileTypeText=culang.kocShortBarbarian;
                    else
                        t.report[reportId].side0TileTypeText=culang.mainCity;

                    t.report[reportId].side0TileTypeLevel = t.report[reportId].side0TileTypeText + ' ' + rpt.side0TileLevel;
                    t.report[reportId].side0TileType = rpt.side0TileType;
                    t.report[reportId].side0TileLevel = rpt.side0TileLevel;
                    t.report[reportId].page = page;
                    t.report[reportId].reportUnixTime = rpt.reportUnixTime;
                    if (rpt.side0AllianceId == parseInt(getMyAlliance()[0]))
                        t.report[reportId].sideId = 0;
                    else if (rpt.side1AllianceId == parseInt(getMyAlliance()[0])) {
                        t.report[reportId].sideId = 1;
                    } else {
                        if (rpt.side0PlayerId == getMyUserId())
                            t.report[reportId].sideId = 0;
                        else if (rpt.side1PlayerId == getMyUserId())
                            t.report[reportId].sideId = 1;
                        else
                            t.report[reportId].sideId = -1;
                    }
                    if (!ById("KsSyntheseAttack").checked && parseInt(rpt.side0TileType) == 54 && Options.rptType=='player') {
                        t.FindItemRpt(reportId, t.report[reportId].sideId, t.report[reportId].side0TileLevel);
                    }
                    if (ById("KsSyntheseAttack").checked && (rpt.marchType == 4 || rpt.marchType == 3))
                    {
                        t.KsSyntheseAttack(reportId, t.report[reportId].sideId, 0);
                    }
                    t.report[reportId].marchType = rpt.marchType;
                    if (rpt.marchType == 0)
                        t.report[reportId].marchName = culang.mainDesertion;
                    else if (rpt.marchType == 1)
                        t.report[reportId].marchName = culang.mainTransport;
                    else if (rpt.marchType == 2)
                        t.report[reportId].marchName = culang.mainReinforced;
                    else if (rpt.marchType == 3 || rpt.marchType == 11) {
                        if (t.report[reportId].sideId == 0)
                            t.report[reportId].marchName = culang.mainAntiScout;
                        else
                            t.report[reportId].marchName = culang.mainScout;
                    } else if (rpt.marchType == 4) {
                        if (t.report[reportId].sideId == 0)
                            t.report[reportId].marchName = culang.mainDefense;
                        else
                            t.report[reportId].marchName = culang.mainAttack;
                    } else if (rpt.marchType == 10 || rpt.marchType == 9) {
                        t.report[reportId].marchName =  culang.mainAttack;
                    } else
                        t.report[reportId].marchName = '?';
                    t.data.push ({
                        reportId: reportId,
                    });
                }
            }
            if (parseInt(page)+1 <= t.maxPages && t.searchRunning) {
                ById("idRptStatus").innerHTML = culang.reportSearchedPages+' ' + (parseInt(page)+1) + ' / ' + t.maxPages;
                t.getRpt(parseInt(page)+1);
                if (t.data.length > 0)
                    t.DisplayRpt();
            } else if (page) {

                if (ById("KsSyntheseAttack").checked) {
                    t.stopSearch ('<a id=KsresumeAT style="color:#ffaaaa" onclick="javascript:void(0);"><u>'+culang.reportAttackSummary+'</u></a>');
                    setTimeout(function() {
                        // ouverture du resume des rapports FS avec Items
                        ById("KsresumeAT").addEventListener ('click', t.AfficheResumeAtk, false);
                    }, 1000);
                } else {

                    if (Options.rptType=='player') {
                        t.stopSearch ('<a id=KsresumeDF style="color:#ffaaaa" onclick="javascript:void(0);"><u>'+culang.reportDarkForestSummary+'</u></a>');
                        setTimeout(function() {
                            // ouverture du resume des rapports FS avec Items
                            ById("KsresumeDF").addEventListener ('click', t.AfficheResume, false);
                        }, 1000);
                    } else {
                        t.stopSearch (''+culang.mainHDone+'');
                    }
                }
            }
        }
    },
    AfficheResumeAtk:function() {
        var t = Tabs.Rpt;
        var puipui=new Array();
        var fortmight = {u53: "4",u55: "7",u60: "1",u61: "2",u62: "3",    };
        for (var ui = 1 ; ui<16; ui++)
            puipui.push(unsafeWindow.unitmight['unt'+ui]);
        puipui[52] = fortmight['u53'];
        puipui[54] = fortmight['u55'];
        puipui[59] = fortmight['u60'];
        puipui[60] = fortmight['u61'];
        puipui[61] = fortmight['u62'];
        var messageBody="";
        reportsSearched = t.dataAT.length;
        reportsFound = 0;
        var tr0=0,tr1=0,tr2=0,tr3=0,tr4=0,tr5=0;
        if (reportsSearched>0) {
            messageBody +='<br><table width=98%><thead><th>'+culang.mainPlayer+'<br>'+uW.g_js_strings.commonstr.alliance+'</th><th><img src="'+IMGgold30+'"></th>\
      <th><img src="'+IMGfood30+'"></th><th><img src="'+IMGwood30+'"></th>\
      <th><img src="'+IMGstone30+'"></th><th><img src="'+IMGiron30+'"></th>\
      <th><img src="'+IMGastone30+'"></th></thead><tbody>';
            t.dataAT.sort(function(a, b){
                var sortA=a.nom,sortB=b.nom;
                if (sortA < sortB) return -1
                if (sortA > sortB) return 1
                return 0
            });
            var datartp = [];
            var nbrp=0;
            for (var i=0; i<reportsSearched;i++) {
                var idrapport=t.dataAT[i].reportId;
                if ((t.what == '' || (t.dataAT[i].nom.search(t.what, "i") != -1)  || (t.dataAT[i].alliance.search(t.what, "i") != -1))
                    && (t.whatNot == '' || (t.dataAT[i].nom.search(t.whatNot, "i") != -1 && t.dataAT[i].alliance.search(t.whatNot, "i") != -1)))
                {

                    if (datartp[nbrp]==undefined) {
                        datartp[nbrp]=[];
                        datartp[nbrp].nom = t.dataAT[i].nom;
                        datartp[nbrp].alliance = t.dataAT[i].alliance;
                        datartp[nbrp].res0=0;
                        datartp[nbrp].res1=0;
                        datartp[nbrp].res2=0;
                        datartp[nbrp].res3=0;
                        datartp[nbrp].res4=0;
                        datartp[nbrp].res5=0;
                        for (var z=1;z<64;z++) {
                            datartp[nbrp]['s1unit'+z] =0;
                            datartp[nbrp]['s0unit'+z] =0;
                        }
                    }
                    if(datartp[nbrp].nom==t.dataAT[i].nom && datartp[nbrp].alliance==t.dataAT[i].alliance) {
                        datartp[nbrp].res0 += parseIntNan(t.reportAT[idrapport].res0);
                        datartp[nbrp].res1 += parseIntNan(t.reportAT[idrapport].res1);
                        datartp[nbrp].res2 += parseIntNan(t.reportAT[idrapport].res2);
                        datartp[nbrp].res3 += parseIntNan(t.reportAT[idrapport].res3);
                        datartp[nbrp].res4 += parseIntNan(t.reportAT[idrapport].res4);
                        datartp[nbrp].res5 += parseIntNan(t.reportAT[idrapport].res5);
                        for (var z=1;z<64;z++) {
                            datartp[nbrp]['s1unit'+z] += parseIntNan(t.reportAT[idrapport]['s1unit'+z]);
                            datartp[nbrp]['s0unit'+z] += parseIntNan(t.reportAT[idrapport]['s0unit'+z]);
                        }
                    } else {
                        nbrp++;
                        datartp[nbrp]=[];
                        datartp[nbrp].nom = t.dataAT[i].nom;
                        datartp[nbrp].alliance = t.dataAT[i].alliance;
                        datartp[nbrp].res0=0;
                        datartp[nbrp].res1=0;
                        datartp[nbrp].res2=0;
                        datartp[nbrp].res3=0;
                        datartp[nbrp].res4=0;
                        datartp[nbrp].res5=0;
                        datartp[nbrp].res0 += parseIntNan(t.reportAT[idrapport].res0);
                        datartp[nbrp].res1 += parseIntNan(t.reportAT[idrapport].res1);
                        datartp[nbrp].res2 += parseIntNan(t.reportAT[idrapport].res2);
                        datartp[nbrp].res3 += parseIntNan(t.reportAT[idrapport].res3);
                        datartp[nbrp].res4 += parseIntNan(t.reportAT[idrapport].res4);
                        datartp[nbrp].res5 += parseIntNan(t.reportAT[idrapport].res5);
                        for (var z=1;z<64;z++) {
                            datartp[nbrp]['s1unit'+z] =0;
                            datartp[nbrp]['s0unit'+z] =0;
                            datartp[nbrp]['s1unit'+z] += parseIntNan(t.reportAT[idrapport]['s1unit'+z]);
                            datartp[nbrp]['s0unit'+z] += parseIntNan(t.reportAT[idrapport]['s0unit'+z]);
                        }
                    }
                }// fin du regrouppement
            }
            reportsSearched = datartp.length;
            var tres=[0,0,0,0,0,0];
            var perts1=[];var perts0=[];
            for (var z=1;z<64;z++) { perts1[z]=0;perts0[z]=0; }

            for (var i=0; i<reportsSearched;i++) {
                messageBody += '<tr><td>'+datartp[i].nom+'<br>'+datartp[i].alliance+'</td>';
                for (var res=0;res<6;res++) {
                    messageBody += '</td><td align=right>';
                    var cb=0;
                    if (datartp[i]["res"+res] != undefined) {
                        cb=parseIntNan(datartp[i]["res"+res]);
                        tres[res]+=cb;
                    }
                    messageBody += addCommas(cb);
                }
                for (var z=1;z<64;z++) {
                    perts1[z]+=parseIntNan(datartp[i]['s1unit'+z]);
                    perts0[z]+=parseIntNan(datartp[i]['s0unit'+z]);
                }
            }
            messageBody += '</td></tr><tr><td><b>'+culang.mainHTotal+': </td>';
            for (var res=0;res<6;res++) messageBody +='<td align=right><b>'+addCommas(tres[res])+'</b></td>';
            messageBody += "</tr></table>";
            messageBody += "<br><table><thead><th width=120><b>"+culang.reportOurLooses+"</b></th>";
            for (var z=1;z<64;z++) {
                if (perts1[z]>0) {
                    messageBody +='<th width=6%><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+z+'_30.jpg ';
                    if(z<16)
                        messageBody +='title="'+unsafeWindow.unitcost['unt'+z][0]+'"';
                    messageBody +='></th>';
                }
            }
            messageBody +='<th></th></thead><tr><td>'+culang.mainAmount+'</td>';
            for (var z=1;z<64;z++) if (perts1[z]>0) messageBody +='<td align=right>'+ addCommas(perts1[z])+'</td>';
            messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+'</td>';
            for (var z=1;z<64;z++) if (perts1[z]>0) messageBody +='<td align=right>'+ addCommas(parseIntNan(perts1[z])*parseIntNan(puipui[z-1]))+'</td>';
            var to1=0;
            messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+' total</td>';
            for (var z=1;z<64;z++) to1+=(parseIntNan(perts1[z])*parseIntNan(puipui[z-1]));
            messageBody += "<td align=right><b>"+addCommas(to1)+"</b></td></tr><thead><th><b>"+culang.reportEnemyLooses+"</b></th>";
            for (var z=1;z<64;z++) {
                if (perts0[z]>0) {
                    messageBody +='<th width=6%><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+z+'_30.jpg ';
                    if(z<16)
                        messageBody +='title="'+unsafeWindow.unitcost['unt'+z][0]+'"';
                    messageBody +='></th>';
                }
            }
            messageBody +='<th></th></thead><tr><td>'+culang.mainAmount+'</td>';
            for (var z=1;z<64;z++) if (perts0[z]>0)messageBody +='<td align=right>'+ addCommas(parseIntNan(perts0[z]))+'</td>';
            messageBody +='<td></td></tr><tr><td>'+uW.g_js_strings.commonstr.might+'</td>';

            for (var z=1;z<64;z++) if (perts0[z]>0)messageBody +='<td align=right>'+ addCommas(parseIntNan(perts0[z])*parseIntNan(puipui[z-1]))+'</td>';
            var to2=0;
            messageBody +='</tr><tr><td>'+culang.reportTotalMight+'</td>';
            for (var z=1;z<64;z++) to2+= (parseIntNan(perts0[z])*parseIntNan(puipui[z-1]));
            messageBody +="<td align=right><b>"+addCommas(to2)+"</b></td></tr></table><br>";

            if (to1<to2)
                messageBody += "<br><b>"+culang.reportMightDifference+" <font color=#449944>"+addCommas((to2-to1))+"</font><br>";
            if (to1==to2)
                messageBody += "<br><b>"+culang.reportNoMightLoose+"<br>";
            if (to1>to2)
                messageBody += "<br><b>"+culang.reportMightDifference+" <font color=#994444>"+addCommas((to1-to2))+"</font><br>";

        } else {
            messageBody +="<br><center>"+culang.reportNoAttackSummary+"<br>";
        }
        t.popRapportAT = new CPopup('pbRapportATBody', 0, 0, 770, 500, true, function() {clearTimeout (1000);});
        t.popRapportAT.centerMe (mainPop.getMainDiv());
        var m = '<DIV style="max-height:465px;">';
        m+= messageBody + '</div>';
        t.popRapportAT.getMainDiv().innerHTML = m;
        t.popRapportAT.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.reportAttackSummaryHead+'</DIV>';
        t.popRapportAT.show(true);
    },
    AfficheResume:function() {
        var t = Tabs.Rpt;
        var messageBody="";
        reportsSearched = t.dataDF.length;
        reportsFound = 0;
        if (t.dataDF.length>0) {
            messageBody +='<br><center><table width=60%><thead><th>'+culang.mainReports+'</th><th>'+uW.g_js_strings.commonstr.level+'</th><th colspan=2>'+culang.mainItems+'</th></thead><tbody>';
            for (var i=0; i<reportsSearched;i++) {
                var idrapport=t.dataDF[i].reportId;
                var rpt =  t.reportDF[idrapport];
                messageBody += '<tr><td align=right><a onclick="getReport('+ idrapport+')">'+idrapport+'</A></td><td>'+rpt.lvl+'</td><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/' + rpt.item + '.jpg></td><td>'+unsafeWindow.ksoItems[rpt.item].name+'</td></tr>';
            }
            messageBody += "</tbody></table>";
        } else {
            messageBody +="<br><center>"+culang.reportNoDarkForestReports+"</center><br>";
        }

        messageBody +='<br><input type=button value="'+culang.reportDeleteDarkForest+'" id=KsDelAllDF></center>';


        t.popRapportDF = new CPopup('pbRapportDFBody', 0, 0, 500, 400, true, function() {clearTimeout (1000);});
        t.popRapportDF.centerMe (mainPop.getMainDiv());

        var m = '<DIV style="max-height:365px;">';
        m+= messageBody + '</div>';
        t.popRapportDF.getMainDiv().innerHTML = m;
        t.popRapportDF.getTopDiv().innerHTML = '<DIV class="popupBanner"><B>'+culang.reportDarkForestSummaryHead+'</B></DIV>';
        t.popRapportDF.show(true);
        ById('KsDelAllDF').addEventListener ('click', t.DeleteRptDF, false);

    },
    pagesasup:0,
    DeleteRptDF:function() {
        var t = Tabs.Rpt;
        t.pagesasup = 0;
        t.fetchreport(0, t.checkreports);
        t.popRapportDF.show(false);
        t.popRapportDF.destroy();
        t.popRapportDF = null;
    },
    fetchreport : function(pageNo, callback){
        var t =  Tabs.Rpt;
        if (t.pagesasup>=t.maxPages) return;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if(pageNo > 1)
            params.pageNo = pageNo;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                t.pagesasup++;
                callback(rslt);
            },
            onFailure: function () {
                t.pagesasup++;
                callback();
            },
        });
    },

    checkreports : function(rslt){
        var t = Tabs.Rpt;
        if(!rslt.ok){
            return;
        }
        if(rslt.arReports.length < 1){
            return;
        }
        var reports = rslt.arReports;
        var totalPages = rslt.totalPages;
        var deletes1 = new Array();
        for(k in reports){
            if(reports[k].side0TileType==54)
                deletes1.push(k.substr(2));

        }
        if(deletes1.length > 0 ){
            t.deleteCheckedReports(deletes1);
        } else {

            return;
        }
    },
    deleteCheckedReports : function(deletes1){
        var t =  Tabs.Rpt;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.s1rids = deletes1.join(",");
        params.cityrids = '';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if(rslt.ok){
                    Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length);
                }
                t.fetchreport(0, t.checkreports);
                t.DisplayRpt();
            },
            onFailure: function () {
            },
        });
    },
    KsSyntheseAttack:function(reportId, sideId, lvl) {
        var t = Tabs.Rpt;
        var rpt = t.report[reportId];
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.rid=reportId;
        params.side=sideId;
        if (params.side > -1) {
            new AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/fetchReport.php"+unsafeWindow.g_ajaxsuffix, {  method:"post",  parameters:params,

                onSuccess:function(msg){
                    var rslt = eval("(" + msg.responseText + ")");
                    t.dataAT.push ({reportId: reportId, nom:rpt.side0Name, alliance:rpt.side0AllianceName});
                    t.reportAT[reportId] = [];
                    t.reportAT[reportId].nom = rpt.side0Name;
                    t.reportAT[reportId].alliance = rpt.side0AllianceName;
                    t.reportAT[reportId].res0=0;
                    t.reportAT[reportId].res1=0;
                    t.reportAT[reportId].res2=0;
                    t.reportAT[reportId].res3=0;
                    t.reportAT[reportId].res4=0;
                    t.reportAT[reportId].res5=0;
                    if (rslt.loot) {
                        if (rslt['loot'][0] !== undefined) t.reportAT[reportId].res0=rslt['loot'][0];
                        if (rslt['loot'][1] !== undefined) t.reportAT[reportId].res1=rslt['loot'][1];
                        if (rslt['loot'][2] !== undefined) t.reportAT[reportId].res2=rslt['loot'][2];
                        if (rslt['loot'][3] !== undefined) t.reportAT[reportId].res3=rslt['loot'][3];
                        if (rslt['loot'][4] !== undefined) t.reportAT[reportId].res4=rslt['loot'][4];
                        if (rslt['loot'][6] !== undefined) t.reportAT[reportId].res5=rslt['loot'][6];
                    }
                    if (sideId==0) { // les pertes !!!!
                        for (var zz=0;zz<6;zz++)
                            t.reportAT[reportId]["res"+zz] = t.reportAT[reportId]["res"+zz] *-1;
                    }
                    if (rslt['fght'] != undefined){
                        if (rslt['fght']["s1"] != undefined) {
                            for (var i=1;i<16;i++) {
                                if (rslt['fght']["s1"]['u'+i] != undefined) {
                                    if (sideId==1) t.reportAT[reportId]['s1unit'+i]=rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1]; // perte 
                                    else t.reportAT[reportId]['s0unit'+i]=rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1]; // perte 

                                }else{
                                    if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
                                    else t.reportAT[reportId]['s0unit'+i]=0;
                                }
                            }
                            for (var i=53;i<=55;i++) {
                                if (rslt['fght']["s1"]['f'+i] != undefined) {
                                    if (sideId==1) t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];
                                    else t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];

                                }else{
                                    if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
                                    else t.reportAT[reportId]['s0unit'+i]=0;
                                }
                            }
                            for (var i=60;i<=63;i++) {
                                if (rslt['fght']["s1"]['f'+i] != undefined) {
                                    if (sideId==1) t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];
                                    else t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s1"]['f'+i][0] - rslt['fght']["s1"]['f'+i][1];

                                }else{
                                    if (sideId==1) t.reportAT[reportId]['s1unit'+i]=0;
                                    else t.reportAT[reportId]['s0unit'+i]=0;
                                }
                            }
                        }
                        if (rslt['fght']["s0"] != undefined) {
                            for (var i=1;i<16;i++) {
                                if (rslt['fght']["s0"]['u'+i] != undefined) {
                                    if (sideId==1) {
                                        t.reportAT[reportId]['s0unit'+i]=rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1]; // perte
                                    }else{
                                        t.reportAT[reportId]['s1unit'+i]=rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1]; // perte
                                    }
                                } else {
                                    if (sideId==1) {
                                        t.reportAT[reportId]['s0unit'+i]=0;
                                    } else {
                                        t.reportAT[reportId]['s1unit'+i]=0;
                                    }
                                }
                            }
                            for (var i=53;i<=55;i++) {
                                if (rslt['fght']["s0"]['f'+i] != undefined) {
                                    if (sideId==1) {
                                        t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
                                    } else {
                                        t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
                                    }
                                }else{
                                    if (sideId==1) t.reportAT[reportId]['s0unit'+i]=0;
                                    else t.reportAT[reportId]['s1unit'+i]=0;
                                }
                            }
                            for (var i=60;i<=63;i++) {
                                if (rslt['fght']["s0"]['f'+i] != undefined) {
                                    if (sideId==1) {
                                        t.reportAT[reportId]['s0unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
                                    } else {
                                        t.reportAT[reportId]['s1unit'+i] = rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1];
                                    }
                                }else{
                                    if (sideId==1) {
                                        t.reportAT[reportId]['s0unit'+i]=0;
                                    } else {
                                        t.reportAT[reportId]['s1unit'+i]=0;
                                    }
                                }
                            }
                        }
                    }

                } });
        }
    },
    FindItemRpt:function(reportId, sideId, lvl) {
        var t = Tabs.Rpt;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.rid=reportId;
        params.side=sideId;
        if (params.side > -1) {
            new AjaxRequest(unsafeWindow.g_ajaxpath+"ajax/fetchReport.php"+unsafeWindow.g_ajaxsuffix, {  method:"post",  parameters:params,

                onSuccess:function(msg){
                    var rslt = eval("(" + msg.responseText + ")");
                    if (rslt.loot) {
                        if (rslt['loot'][5] !== undefined) {
                            var q=unsafeWindow.Object.keys(rslt['loot'][5]);
                            if (q.length>0) {
                                for(var u=0,y=q.length;u<y;++u){
                                    C=q[u];
                                    if (unsafeWindow.ksoItems[C]!==undefined) {
                                        t.dataDF.push ({reportId: reportId,});
                                        t.reportDF[reportId] = [];
                                        t.reportDF[reportId].lvl = lvl;
                                        t.reportDF[reportId].item = C;
                                    }
                                }
                            }


                        }

                    }
                }
            });
        }

    },
    DisplayMail: function (){
        var t = Tabs.Rpt;
        var results = ById("idBoRptResultsDiv");
        if(!t.data.length) {
            results.innerHTML = '<center><i><b>'+culang.reportNoResults+'</b></i></center>';
            return;
        }
        reportsSearched = t.data.length;
        reportsFound = 0;
        t.content = '';
        for (var i=0; i<reportsSearched;i++) {
            var rpt = t.data[i];
            if ((t.what == '' || (rpt.subject.search(t.what, "i") != -1) || (rpt.displayName.search(t.what, "i") != -1))
                && (t.whatNot == '' || ((rpt.subject.search(t.whatNot, "i") == -1) && (rpt.displayName.search(t.whatNot, "i") == -1)))) {
                if (rpt.subject == '')
                    rpt.subject = ''+culang.mainNoSubject+'';
                reportsFound++;
                if (reportsFound == 1)
                    t.content += '<center><table width=97%><thead><th title="'+culang.mainPage+'"><b><u>'+culang.shortPage+'</u></b></th><th><b><u>'+culang.mainDate+'</u></b></th><th><b><u>'+culang.mainFrom+'</u></b></th><th><b><u>'+culang.mainSubject+'</u></b></th><th><b><u>'+culang.mainDelete+'</u></b></th></thead><tbody>';
                var stylee="";
                if (rpt.messageRead==0) stylee=' style="background-color:#CCCCCC;"';
                t.content += '<tr><td align=right '+stylee+'>'+rpt.page+'</td><td '+stylee+'>'+rpt.dateSent+'</td><td '+stylee+'>'+rpt.displayName+'</td>';
                t.content += '<td '+stylee+'><A><SPAN onclick="getmsg('+ rpt.messageId +')">' + rpt.subject + '</SPAN></a></td><td><a onclick="DelMail('+ rpt.messageId +');"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.reportDeleteMessageNote+'" alt="'+culang.mainDelete+'"></a></td></tr>';
            }
        }
        if (reportsFound > 1)
            t.content += '</tbody></table></center>';
        if (reportsFound == 0 && reportsSearched > 0)
            t.content = '<center><i><b>'+culang.reportNoResults+'</b></i></center>';
        results.innerHTML = t.content;
        ById("idRptSearched").innerHTML = '&nbsp;'+culang.reportSearched+' ' + reportsSearched;
        ById("idRptFound").innerHTML = ''+culang.reportFound+' ' + reportsFound;
    },

    getMailBody: function(ID,dataI){
        var t = Tabs.Rpt;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.messageId=ID;
        params.requestType="GET_MESSAGE_FOR_ID";

        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok)
                    t.displayMailBody(rslt.messageBody, ID);
            },
            onFailure: function () {},
        }, false);
    },

    displayMailBody: function (messageBody, ID) {
        var t = Tabs.Rpt;
        if (t.popMsg == null) {
            t.popMsg = new CPopup('pbMailBody', 0, 0, 670, 500, true, function() {clearTimeout (1000);});
            t.popMsg.centerMe (mainPop.getMainDiv());
        }
        messageBody=messageBody.replace(/custom-line-break/g,"<br>");
        var m = '<DIV style="max-height:465px;"><br><hr>';
        m+= messageBody + '<hr><a onclick="DelMail('+ ID +');"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.reportDeleteMessageNote+'" alt="'+culang.mainDelete+'"></a><br></div>';
        t.popMsg.getMainDiv().innerHTML = m;
        t.popMsg.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.mainMessage+'</DIV>';
        t.popMsg.show(true);
    },

    DisplayRpt: function (){
        var t = Tabs.Rpt;
        var results = ById("idBoRptResultsDiv");
        if(!t.data.length) {
            results.innerHTML = '<center><i><b>'+culang.reportNoResults+'</b></i></center>';
            return;
        }
        var myAllianceId = parseInt(getMyAlliance()[0]);
        reportsSearched = t.data.length;
        reportsFound = 0;
        t.content = '';
        for (var i=0; i<reportsSearched;i++) {
            var reportId = t.data[i].reportId;
            var rpt = t.report[reportId];
            if ((rpt.side0Name=='undefined') && (rpt.marchName != ''+culang.mainDesertion+''))
                continue;
            if ((((myAllianceId == parseInt(rpt.side1AllianceId) && Options.arAttacker != 'Them')
                || (myAllianceId != parseInt(rpt.side1AllianceId) && Options.arAttacker != 'Us')
                || Options.arAttacker == 'Both')
                && ((myAllianceId == parseInt(rpt.side0AllianceId) && Options.arTarget != 'Them')
                || (myAllianceId != parseInt(rpt.side0AllianceId) && Options.arTarget != 'Us')
                || Options.arTarget == 'Both')
                && ((Options.arAttack && (rpt.marchName ==  ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+''))
                || (Options.arScout && (rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainScout+''))
                || (Options.arReinforce && rpt.marchName == ''+culang.mainReinforced+'')
                || (Options.arTransport && rpt.marchName == ''+culang.mainTransport+'')))
                || (rpt.marchName == ''+culang.mainDesertion+'')) {
                if (((t.what == ''
                    || (rpt.side1Name.search(t.what, "i") != -1)
                    || (rpt.side1AllianceName.search(t.what, "i") != -1)
                    || (rpt.side0Name.search(t.what, "i") != -1)
                    || (rpt.side0AllianceName.search(t.what, "i") != -1)
                    || (rpt.side0TileTypeText.search(t.what, "i") != -1))
                    && (t.whatNot == ''
                    || ((rpt.side1Name.search(t.whatNot, "i") == -1)
                    && (rpt.side1AllianceName.search(t.whatNot, "i") == -1)
                    && (rpt.side0Name.search(t.whatNot, "i") == -1)
                    && (rpt.side0AllianceName.search(t.whatNot, "i") == -1)
                    && (rpt.side0TileTypeText.search(t.whatNot, "i") == -1))))
                    || (rpt.marchName == ''+culang.mainDesertion+'')) {

                    if ((ById("idRptFiltre1").value=="") ||   (rpt.side0TileType==54 && ById("idRptFiltre1").value==54)  ||
                        (rpt.side0TileType>0 && rpt.side0TileType<51 && ById("idRptFiltre1").value==0)) {


                        reportsFound++;
                        if (reportsFound == 1) {
                            t.content += '<center><table class=pdxTabOverview width=100% cellspacing=0 cellpadding=3><thead><th title="'+culang.mainPage+'"><b><u>'+culang.shortPage+'</u></b></th><th title="'+culang.mainAction+'"><b><u>'+culang.shortAction+'</u></b></th><th><b><u>'+culang.mainDate+'</u></b></th><th><b><u>'+culang.mainAttacker+'</u></b></th><th><b><u>'+culang.shortCoordinate+'</u></b></th>';
                            if (Options.arAttacker != 'Us')
                                t.content += '<th><b><u>'+uW.g_js_strings.commonstr.alliance+'</u></b></th>';
                            t.content += '<th><b><u>'+culang.reportMarchType+'</u></b></th><th><b><u>'+culang.mainTarget+'</u></b></th><th><b><u>'+culang.shortCoordinate+'</u></b></th>';
                            if (Options.arTarget != 'Us')
                                t.content += '<th><b><u>'+uW.g_js_strings.commonstr.alliance+'</u></b></th>';
                            t.content += '<th><b><u>'+culang.mainType+'</u></b></th><th><span title="'+culang.reportNextCity+'"><b><u>'+culang.mainSRallyPoint+'</u></b></span></th><th><span title="'+culang.reportShortDistanceNote+'"><b><u>'+culang.reportShortDistance+'</u></b></span></th></thead><tbody>';
                        }


                        var closestDist=999999;
                        var closestLoc=null;
                        var closestNum=1;
                        for (var c=0; c<Cities.numCities; c++){
                            var city = Cities.cities[c];
                            var dist=distance(city.x,city.y,rpt.side0XCoord,rpt.side0YCoord);
                            if(dist<closestDist) {
                                closestDist=dist;
                                closestLoc=city.x +','+ city.y;
                                closestNum=c+1;
                            }
                        }
                        if (rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainDefense+'')
                            style=' style="background-color:#EF9999;"';
                        else if (rpt.marchName == ''+culang.mainReinforced+'')
                            style=' style="background-color:#99EF99;"';
                        else
                            style="";
                        t.content += '<tr id="Ksrpt'+ reportId +'"><td align=right '+style+'>'+rpt.page+'</td><td  align=right '+style+'><a onclick="getReport('+ reportId+')"><img  border=0 src="'+IMGshowButton+'" title="'+culang.mainShow+'"></a>';
                        if (rpt.side0Name==Seed.player.name || rpt.side1Name==Seed.player.name) {
                            t.content +='&nbsp;<a onclick="DelReport('+ reportId +', false);document.getElementById(\'Ksrpt'+ reportId +'\').style.display=\'none\';"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.reportDeleteNowNote+'"></a>';
                        }
                        t.content += '</td><td '+style+'>'+formatDate(rpt.reportUnixTime,DATETIME_STR)+'</td>';
                        if (rpt.marchName == ''+culang.mainDesertion+'') {
                            t.content += '<td '+style+'></td><td '+style+'></td>';
                            if (Options.arAttacker != 'Us')
                                t.content += '<td '+style+'></td>';
                            t.content += '<td '+style+'>'+rpt.marchName+'</td><td '+style+'></td><td '+style+'></td><td '+style+'></td>';
                            if (Options.arAttacker != 'Us')
                                t.content += '<td '+style+'></td>';
                            t.content += '<td '+style+'></td><td '+style+'></td>';
                        } else {
                            t.content += '<td '+style+'><span title="'+rpt.side1Name+'">'+rpt.side1Name.substring(0,12)+'</span></td><td align=center '+style+'><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a></td>';
                            if (Options.arAttacker != 'Us')
                                t.content += '<td '+style+'><span title="'+rpt.side1AllianceName+'">'+rpt.side1AllianceName.substring(0,17)+'</span></td>';
                            if (rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainScout+'')
                                t.content += '<TD '+style+'><FONT color="black">'+rpt.marchName+'</font></td>';
                            else if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')
                                t.content += '<TD '+style+'><FONT color="black">'+rpt.marchName+'</font></td>';
                            else if (rpt.marchName == ''+culang.mainReinforced+'')
                                t.content += '<TD '+style+'><FONT color="black">'+rpt.marchName+'</font></td>';
                            else
                                t.content += '<TD '+style+'>'+rpt.marchName+'</td>';
                            //t.content += '<td>'+rpt.marchName+'</td>';
                            t.content += '<td '+style+'><span title="'+rpt.side0Name+'">'+rpt.side0Name.substring(0,12)+'</span></td>';
                            t.content += '<td align=center '+style+'><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a></td>';
                            if (Options.arTarget != 'Us')
                                t.content += '<td '+style+'><span title="'+rpt.side0AllianceName+'">'+rpt.side0AllianceName.substring(0,17)+'</span></td>';
                            t.content += '<td '+style+'>'+rpt.side0TileTypeLevel+'</td><td align=center '+style+'><A onclick=\"citysel_click(document.getElementById(\'citysel_'+ (closestNum)+'\'));\">' + closestLoc + '</a></td><td align=right '+style+'>'+Math.floor(closestDist)+'</td></tr>';
                        }
                    }
                }
            }
        }
        if (reportsFound > 1)
            t.content += '</tbody></table></center>';
        if (reportsFound == 0 && reportsSearched > 0)
            t.content = '<center><b><i>'+culang.reportNoResults+'</i></b></center>';
        results.innerHTML = t.content;
        ById("idRptSearched").innerHTML = '&nbsp;'+culang.reportSearched+' ' + reportsSearched;
        ById("idRptFound").innerHTML = ''+culang.reportFound+' ' + reportsFound;
        //Chatausgabe wenn AutoScan aktiviert
        if (Options.reportScanner.start) {
            for (var i=0; i<reportsSearched;i++) {
                var reportId = t.data[i].reportId;
                var rpt = t.report[reportId];
                if (rpt.side0Name == 'undefined') continue;
                if (LastUnixTime >= rpt.reportUnixTime) continue;
                if (rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainDefense+'') {
                    //'BERICHT auf Seite {page} / Typ: {type} / Zeit: {time} / {attacker} / {member} braucht evtl. Hilfe / Bericht: {report}';
                    var rep = {
                        'page'     : rpt.page,
                        'type'     : rpt.marchName,
                        'time'     : formatDate(rpt.reportUnixTime,DATETIME_STR),
                        'attacker' : rpt.side1Name + ' (' + rpt.side1XCoord + ',' + rpt.side1YCoord + ') ' + rpt.side1AllianceName,
                        'member'   : rpt.side0Name + ' (' + rpt.side0XCoord + ',' + rpt.side0YCoord + ')',
                        'report'   : '#' + reportId + '#',
                    };
                    var msg = culang.reportScannerChatMsg.mreplace(rep);
                    if (Options.reportScanner.lastmsg != rpt.reportUnixTime) sendChat("/a " + msg);
                    Options.reportScanner.lastmsg = rpt.reportUnixTime;
                    LastUnixTime = rpt.reportUnixTime;
                }
            }
            saveOptions();
        }
    },

    getReportBody: function(reportId){
        var t = Tabs.Rpt;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.rid=parseInt(reportId);
        params.side=t.report[reportId].sideId;
        if (params.side > -1) {
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchReport.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    t.displayReportBody(rslt,reportId);
                },
                onFailure: function (rslt) {},
            }, false);
        } else {

        }
    },

    getReportBodyAC : function(rpId) {
        var t = Tabs.Rpt;
        var params = uW.Object.clone(uW.g_ajaxparams);
            params.rid=rpId;
            new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchReport.php" + uW.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    var rpt = rslt['index'];
                    rpt.Side0PlayerId = rslt['index']['side0PlayerId'];
                    rpt.Side0AllianceId = rslt['index']['side0AllianceId'];
                    rpt.Side1PlayerId = rslt['index']['side1PlayerId'];
                    if (rpt.marchType == 0)
                        rpt.marchName = culang.mainDesertion;
                    else if (rpt.marchType == 1)
                        rpt.marchName = culang.mainTransport;
                    else if (rpt.marchType == 2)
                        rpt.marchName = culang.mainReinforced;
                    else if (rpt.marchType == 3 || rpt.marchType == 11) {
                        if (rpt.sideId == 0)
                            rpt.marchName = culang.mainAntiScout;
                        else
                            rpt.marchName = culang.mainScout;
                    } else if (rpt.marchType == 4) {
                        if (rpt.sideId == 0)
                            rpt.marchName = culang.mainDefense;
                        else
                            rpt.marchName = culang.mainAttack;
                    } else if (rpt.marchType == 10 || rpt.marchType == 9) {
                        rpt.marchName =  culang.mainAttack;
                    } else
                        rpt.marchName = '?';
                        
                    if (parseInt(rpt.side0TileType) == 10)
                        rpt.side0TileTypeText=culang.kocGrassland;
                    else if (parseInt(rpt.side0TileType) == 11)
                        rpt.side0TileTypeText=culang.kocLake;
                    else if (parseInt(rpt.side0TileType) == 20)
                        rpt.side0TileTypeText=culang.kocForests;
                    else if (parseInt(rpt.side0TileType) == 30)
                        rpt.side0TileTypeText=culang.kocHill;
                    else if (parseInt(rpt.side0TileType) == 40)
                        rpt.side0TileTypeText=culang.kocMount;
                    else if (parseInt(rpt.side0TileType) == 50)
                        rpt.side0TileTypeText=culang.kocPlain;
                    else if (parseInt(rpt.side0TileType) == 51 && parseInt(rpt.side0CityId) == 0)
                        rpt.side0TileTypeText=culang.mainCity;
                    else if (parseInt(rpt.side0TileType) == 54)
                        rpt.side0TileTypeText=culang.shortDarkForest;
                    else if (parseInt(rpt.side0CityId) == 0)
                        rpt.side0TileTypeText=culang.kocShortBarbarian;
                    else
                        rpt.side0TileTypeText=culang.mainCity;

                    t.GetNames(rpId,rpt);
                },
                onFailure: function () {
                    alert('kabam is having issues');
                },
            }, false);
    },


    GetNames : function(rpId,rpt) {
        var t = Tabs.Rpt;
        var params = uW.Object.clone(uW.g_ajaxparams);
            params.uid=rpt.Side0PlayerId;
            new MyAjaxRequest(uW.g_ajaxpath + "ajax/getUserGeneralInfo.php" + uW.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    rpt.side0Name = rslt['userInfo']['0']['name'];
                    var params = uW.Object.clone(uW.g_ajaxparams);
                        params.uid=rpt.Side1PlayerId;
                        new MyAjaxRequest(uW.g_ajaxpath + "ajax/getUserGeneralInfo.php" + uW.g_ajaxsuffix, {
                            method: "post",
                            parameters: params,
                            onSuccess: function (rslt) {
                                rpt.side1Name = rslt['userInfo']['0']['name'];
                                t.GetReport(rpId,rpt);                    
                            },
                            onFailure: function () {
                                alert('kabam is having issues');
                            },
                        }, false);
                },                    
                onFailure: function () {
                    alert('kabam is having issues');
                },
            }, false);
    },

    GetReport: function(rpId, rpt){
        var t = Tabs.Rpt;
        var params = uW.Object.clone(uW.g_ajaxparams);
        if (parseInt(rpt.side0AllianceId) == parseInt(Seed.allianceDiplomacies.allianceId)) {
            params.side = 0;
        } else {
            params.side = 1;
        }
        params.rid=rpId;
            new MyAjaxRequest(uW.g_ajaxpath + "ajax/fetchReport.php" + uW.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    if(rslt.error_code)
                        alert('found report but kabam would not let me see it');
                    else {
                        t.displayReportBody(rslt, rpId, rpt);
                    }
                },
                onFailure: function (rslt) {
                    
                },
            }, false);
    },
    
    displayReportBody: function (rslt, reportId, rpt) {
        var t = Tabs.Rpt;
        var popReport = null;
        if (rpt == null) var rpt = t.report[reportId];
        var m = '';
        var fortmight = {u53: "4",u55: "7",u60: "1",u61: "2",u62: "3",    };
        var unitImg = [];
        var puipui=new Array();
        for (var ui = 1 ; ui<14; ui++)
            puipui.push(uW.unitmight['unt'+ui]);
        puipui[53] = fortmight['u53'];
        puipui[55] = fortmight['u55'];
        puipui[60] = fortmight['u60'];
        puipui[61] = fortmight['u61'];
        puipui[62] = fortmight['u62'];
        ordre_grandeur=0;
        delta_perte=0;
        var perte_atk = 0;
        var perte_def = 0;
        for (var i=1;i<16;i++)
            unitImg[i] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+i+'_30_s34.jpg title="'+uW.unitcost['unt'+i][0]+'"></TD><TD>' + uW.unitcost['unt'+i][0].substr(0,10);
        for (var i=101;i<111;i++)
            unitImg[i] = '<img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+i+'_30.jpg title="'+uW.g_js_strings.monsterUnitsNames['m'+i]+'"></TD><TD>' + uW.g_js_strings.monsterUnitsNames['m'+i].substr(0,10);
        unitImg[53] = '<img height=20 src="'+IMGmiddleCrossbows+'"></TD><TD>'+ uW.fortcost.frt53[0];
        unitImg[55] = '<img height=20 src="'+IMGmiddleTrebuchet+'"></TD><TD>'+ uW.fortcost.frt55[0];
        unitImg[60] = '<img height=20 src="'+IMGmiddleTrap+'"></TD><TD>'+ uW.fortcost.frt60[0];
        unitImg[61] = '<img height=20 src="'+IMGmiddleCaltr+'"></TD><TD>'+ uW.fortcost.frt61[0];
        unitImg[62] = '<img height=20 src="'+IMGmiddleSpiked+'"></TD><TD>' + uW.fortcost.frt62[0];
        goldImg = '<img src="'+IMGgold30+'"></TD><TD>' + uW.g_js_strings.commonstr.gold;
        foodImg = '<img src="'+IMGfood30+'"></TD><TD>' + uW.g_js_strings.commonstr.food;
        woodImg = '<img src="'+IMGwood30+'"></TD><TD>' + uW.g_js_strings.commonstr.wood;
        stoneImg = '<img src="'+IMGstone30+'"></TD><TD>' + uW.g_js_strings.commonstr.stone;
        oreImg = '<img src="'+IMGiron30+'"></TD><TD>' + uW.g_js_strings.commonstr.ore;
        aetherstoneImg = '<img src="'+IMGastone30+'"></TD><TD>'+ uW.g_js_strings.commonstr.aetherstone;

        function buildHeader () {
            var h='<TABLE class=pdxTab width=100%>';
            h+='<TR valign=top><TD align=left width=10%><B>';
            if (rpt.marchName == ''+culang.mainAntiScout+'')
                h+=''+culang.reportAntiScout+' ';
            else if (rpt.marchName == ''+culang.mainScout+'')
                h+=uW.g_js_strings.modal_messages_viewreports_view.scoutrpt+' ';
            else if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')
                h+=uW.g_js_strings.modal_messages_viewreports_view.battleat+' ';

            else if (rpt.marchName == ''+culang.mainReinforced+'' || rpt.marchName == ''+culang.mainTransport+'')
                h+=rpt.marchName+' <u>'+culang.mainFrom+'</u><BR />'+rpt.marchName+' <u>'+culang.mainTo+'</u></B>';
            else if (rpt.marchName == ''+culang.mainTransport+'')
                h+=rpt.marchName+' <u>'+culang.mainFrom+'</u><BR />'+uW.g_js_strings.modal_messages_viewreports_view.transpto+'</B>';
            if (rpt.side0TileTypeText == ''+culang.kocShortBarbarian+'')
                h+=' '+culang.kocBarbarianCamps+' '+uW.g_js_strings.commonstr.level+' ' + rpt.side0TileLevel;
            else if (rpt.side0TileTypeText != ''+culang.mainCity+'')
                h+=' '+rpt.side0TileTypeText+' '+uW.g_js_strings.commonstr.level+' '+ rpt.side0TileLevel+' ';
            h+='</B>';
            if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'' || rpt.marchName == ''+culang.mainAntiScout+'' || rpt.marchName == ''+culang.mainScout+'')
                if (rslt['displayGlory']!==undefined)
                    h+='<br><B>'+uW.g_js_strings.commonstr.glory+': <font color=red>'+rslt['glory']+'</font></B>';

            h+='</td>';
            if (rpt.marchName == ''+culang.mainReinforced+'' || rpt.marchName == ''+culang.mainTransport+'') {
                h+='<TD align=left width=1%>';
                if (Seed.player.name != rpt.side1Name)
                    h+=rpt.side1Name;
                if (Seed.player.name != rpt.side0Name)
                    h+='<BR />'+rpt.side0Name;
                h+='</TD>';
            }
            h+='<TD align=left width=5%>';

            if (rpt.marchName == ''+culang.mainReinforced+'' || rpt.marchName == ''+culang.mainTransport+'')
                h+='<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a><BR />';
            h+='<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a></TD>';

            if (rpt.side0TileTypeText != ''+culang.mainCity+'' && rpt.side0TileTypeText != ''+culang.kocShortBarbarian+'' && (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')) {
                if (rslt['conquered']==1)
                    h+='<TD><FONT color="#CC0000"><B>'+uW.g_js_strings.commonstr.conquered+'</B></font></td>';
                else if (rslt['conquered']==0)
                    h+='<TD><FONT color="#66CC33"><B>'+culang.mainSecured+'</B></font></td>';
            } else if (rpt.marchName == ''+culang.mainReinforced+'' || rpt.marchName == ''+culang.mainTransport+'') {
                h+='<TD align=left width=5%>'+rpt.side1CityName+'<BR />';
                if (rpt.side0CityName != '')
                    h+=rpt.side0CityName+'</TD>';
                else
                    h+=rpt.side0TileTypeText+' '+uW.g_js_strings.commonstr.level+' '+ rpt.side0TileLevel+'</TD>';
            }

            h+='<TD align=right>' + formatUnixTime(rpt.reportUnixTime,'24hour') + '<BR />&nbsp;';
            if (rpt.side0Name==Seed.player.name || rpt.side1Name==Seed.player.name)
                h+='<a onclick="DelReport('+ reportId +', false);ById(\'Ksrpt'+ reportId +'\').style.display=\'none\';ById(\'pbShowOther_X\').click();"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.reportDeleteNowNote+'"></a>';

            h+='&nbsp;'+uW.g_js_strings.modal_messages_viewreports_view.reportno+' ' + reportId + '</TD></TR></TABLE>';
            return h;
        }

        function handleunts () { // Troops sent to Reinforce or troops found on a Scout
            var hunts = '', th = '', tc = '', tf = '';
            if (rslt['unts'] != undefined) {
                if (rpt.marchName == ''+culang.mainReinforced+'')
                    th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+culang.reportReinforcement+'</TH></TR>';
                else if (rslt['unts']['u1'] != undefined || rslt['unts']['u2'] != undefined || rslt['unts']['u3'] != undefined || rslt['unts']['u4'] != undefined || rslt['unts']['u5'] != undefined || rslt['unts']['u6'] != undefined || rslt['unts']['u7'] != undefined || rslt['unts']['u8'] != undefined || rslt['unts']['u9'] != undefined || rslt['unts']['u10'] != undefined || rslt['unts']['u11'] != undefined || rslt['unts']['u12'] != undefined)
                    th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.troops+'</TH></TR>';
                for (var i=1;i<16;i++)
                    if (rslt['unts']['u'+i] != undefined)
                        tc+='<TR><TD>' + unitImg[i] + '</TD><TD align=right>'+addCommas(rslt['unts']['u'+i])+'</TD></TR>';

                tf='</TABLE>';
            }
            if (tc != '')
                hunts = th + tc + tf;
            return hunts;
        }

        function handlersc () { // Resources brought with reinforcements or found on a Scout
            var hrsc = '', th = '', tc = '', tf = '';
            if (rslt['rsc'] != undefined) {
                if (rslt['rsc']['r1'] > 0 || rslt['rsc']['r2'] > 0 || rslt['rsc']['r3'] > 0 || rslt['rsc']['r4'] > 0) {
                    if (rpt.marchName == ''+culang.mainReinforced+'')
                        th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.resources+'</TH></TR>';
                    else {
                        th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.commonstr.resources+'</TH></TR>';
                        if (rslt['gld'] > 0)
                            tc+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommasInt(rslt['gld'])+'</TD></TR>';
                    }
                    if (rslt['rsc']['r1'] > 0)
                        tc+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r1'])+'</TD></TR>';
                    if (rslt['rsc']['r2'] > 0)
                        tc+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r2'])+'</TD></TR>';
                    if (rslt['rsc']['r3'] > 0)
                        tc+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r3'])+'</TD></TR>';
                    if (rslt['rsc']['r4'] > 0)
                        tc+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommasInt(rslt['rsc']['r4'])+'</TD></TR>';
                    tf='</TABLE>';
                }
            }
            if (tc != '')
                hrsc = th + tc + tf;
            return hrsc;
        }

        function handlefrt () { // Fortifications found on a Scout
            var hfrt = '', th = '', tc = '', tf = '';
            if (rslt['frt'] != undefined) {
                if (rslt['frt']['f53'] != undefined || rslt['frt']['f55'] != undefined || rslt['frt']['f60'] != undefined || rslt['frt']['f61'] != undefined || rslt['frt']['f62'] != undefined) {
                    th='<TABLE class=pdxTab><TR><TH colspan=3 align=left>'+uW.g_js_strings.modal_openWalls.walldef+'</TH></TR>';
                    if (rslt['frt']['f53'] != undefined)
                        tc+='<TR><TD>' + unitImg[53] + '</TD><TD align=right>'+addCommas(rslt['frt']['f53'])+'</TD></TR>';
                    if (rslt['frt']['f55'] != undefined)
                        tc+='<TR><TD>' + unitImg[55] + '</TD><TD align=right>'+addCommas(rslt['frt']['f55'])+'</TD></TR>';
                    if (rslt['frt']['f60'] != undefined)
                        tc+='<TR><TD>' + unitImg[60] + '</TD><TD align=right>'+addCommas(rslt['frt']['f60'])+'</TD></TR>';
                    if (rslt['frt']['f61'] != undefined)
                        tc+='<TR><TD>' + unitImg[61] + '</TD><TD align=right>'+addCommas(rslt['frt']['f61'])+'</TD></TR>';
                    if (rslt['frt']['f62'] != undefined)
                        tc+='<TR><TD>' + unitImg[62] + '</TD><TD align=right>'+addCommas(rslt['frt']['f62'])+'</TD></TR>';
                    tf='</TABLE>';
                }
            }
            if (tc != '')
                hfrt = th + tc + tf;
            return hfrt;
        }

        function handleblds (bType) {
            if (rslt['blds'] != undefined) {

                var blds = rslt['blds']['b'+bType];
                var couleur='';
                if (bType==8) couleur=' style="background-color:red"';
                b = '<TR><TD '+couleur+'>'; arField = [], firstbld = true;
                b+=unsafeWindow.buildingcost["bdg"+bType][0]+'</TD><TD '+couleur+'>';
                for (var i=1; i<12; i++)
                    arField[i]=0;
                for (var i=0; i < blds.length; i++)
                    arField[blds[i]]++
                for (var i=11; i>0; i--) {
                    if (arField[i] > 0) {
                        if (firstbld)
                            firstbld = false;
                        else
                            b+=', ';
                        if (arField[i] > 1)
                            b+=arField[i] + ' x ';
                        b+=' ' + i;
                    }
                }
                b+='</TD></TR>';
            } else {
                b='';
            }
            return b;
        }

        if (t.popReport == null) {
            if (rpt.marchName == ''+culang.mainReinforced+'') {
                t.popReport = new CPopup('pbShowRein', 0, 0, 425, 340, true, function() {clearTimeout (1000);});
                m+= '<DIV style="max-height:285px">';
            } else if (rpt.marchName == ''+culang.mainTransport+'') {
                t.popReport = new CPopup('pbShowTrans', 0, 0, 525, 240, true, function() {clearTimeout (1000);});
                m+= '<DIV style="max-height:185px">';
            } else if (rpt.marchName == ''+culang.mainScout+'' && rslt['winner']==1 && rpt.sideId==1){
                t.popReport = new CPopup('pbShowOther', 0, 0, 550, 500, true, function() {clearTimeout (1000);});
                m+= '<DIV style="max-height:485px; ">';
            } else {
                t.popReport = new CPopup('pbShowOther', 0, 0, 630, 440, true, function() {clearTimeout (1000);});
                m+= '<DIV style="max-height:423px; ">';
            }
            t.popReport.centerMe (mainPop.getMainDiv());
            t.popReport.autoHeight (true);
        }
        m+=buildHeader();

        if (rpt.marchName == ''+culang.mainTransport+'') { // Transport
            m+='<TABLE class=pdxTab>'; // Only transports have these in rslt, so handle them here
            if (parseInt(rslt['gold']) > 0)
                m+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommas(rslt['gold'])+'</TD></TR>';
            if (parseInt(rslt['resource1']) > 0)
                m+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommas(rslt['resource1'])+'</TD></TR>';
            if (parseInt(rslt['resource2']) > 0)
                m+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommas(rslt['resource2'])+'</TD></TR>';
            if (parseInt(rslt['resource3']) > 0)
                m+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommas(rslt['resource3'])+'</TD></TR>';
            if (parseInt(rslt['resource4']) > 0)
                m+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommas(rslt['resource4'])+'</TD></TR>';
            if (parseInt(rslt['resource5'])> 0)
                m+='<TR><TD>'+aetherstoneImg+'</TD><TD align=right>'+addCommas(rslt['resource5'])+'</TD></TR>';
            m+='</TABLE>';
        }

        m+='<TABLE class=pdxTab>';
        if ((rslt['winner']==1 && rpt.sideId==0) || (rslt['winner']==0 && rpt.sideId==1)) {
            if (rpt.marchName == ''+culang.mainScout+'')
                m+='<TR><TD><FONT color="#CC0000"><B>'+uW.g_js_strings.modal_messages_viewreports_view.scoutfail+'</B></font></TD></TR>';
            else
                m+='<TR><TD><FONT color="#CC0000"><B>'+uW.g_js_strings.commonstr.defeat+'</B></font></TD></TR>';
        }
        if (rslt['winner']==0 && rpt.sideId==0)
            m+='<TR><TD><FONT color="#66CC33"><B>'+uW.g_js_strings.commonstr.victory+' !</B></font></TD></TR>';
        if (rslt['winner']==1 && rpt.sideId==1)
            m+='<TR><TD><FONT color="#66BB33"><B>'+uW.g_js_strings.commonstr.victory+' !</B></font></TD></TR>';

        if (rslt['wall'] != undefined) {


            if (rslt['wall'] > 0 && rslt['wall'] < 100)
                m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.wallbreach+' '+rslt['wall']+' '+uW.g_js_strings.modal_messages_viewreports_view.percdamage+'</TD></TR>';
            else
                m+='<TR><TD>'+ uW.g_js_strings.modal_messages_viewreports_view.wallbreach+'</TD></TR>';
        }
        m+= '</TABLE><BR />';
        if (rslt['wonGloryItem']) {
            m+="<TABLE class=pdxTab><TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/" + rslt['wonGloryItem'] + ".jpg></td><td colspan=2>"+unsafeWindow.ksoItems[rslt['wonGloryItem']].name+"</td></tr></TABLE><BR />";
        }
        //Throne
        if (rslt['throneRoomDrop']) {
            var A=rslt['throneRoomDrop'];
            faction=A.faction;
            if (unsafeWindow.kocThroneItems[rslt['throneRoomDrop'].id]) {
                var name=unsafeWindow.kocThroneItems[rslt['throneRoomDrop'].id].name;

                m+="<TABLE class=pdxTab><TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/"+faction.replace('briton','britton')+"/"+faction.replace('briton','britton')+"_"+A.type+"_normal_1.png></td><td colspan=2>"+name+"</td></tr></TABLE><BR />";
            }
        }

        if (rslt['loot'] != undefined) {
            m+='<TABLE class=pdxTab>';
            if (rslt['loot'][0] > 0)
                m+='<TR><TD>'+goldImg+'</TD><TD align=right>'+addCommas(rslt['loot'][0])+'</TD></TR>';
            if (rslt['loot'][1] > 0)
                m+='<TR><TD>'+foodImg+'</TD><TD align=right>'+addCommas(rslt['loot'][1])+'</TD></TR>';
            if (rslt['loot'][2] > 0)
                m+='<TR><TD>'+woodImg+'</TD><TD align=right>'+addCommas(rslt['loot'][2])+'</TD></TR>';
            if (rslt['loot'][3] > 0)
                m+='<TR><TD>'+stoneImg+'</TD><TD align=right>'+addCommas(rslt['loot'][3])+'</TD></TR>';
            if (rslt['loot'][4] > 0)
                m+='<TR><TD>'+oreImg+'</TD><TD align=right>'+addCommas(rslt['loot'][4])+'</TD></TR>';
            if (rslt['loot'][6] > 0)
                m+='<TR><TD>'+aetherstoneImg+'</TD><TD align=right>'+addCommas(rslt['loot'][6])+'</TD></TR>';
            if (rslt['loot'][5] !== undefined) {
                var q=unsafeWindow.Object.keys(rslt['loot'][5]);
                if (q.length>0) {
                    for(var u=0,y=q.length;u<y;++u){
                        C=q[u];
                        if (unsafeWindow.ksoItems[C]!==undefined)
                            m+="<TR><td><img width=30 src=https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/" + C + ".jpg></td><td colspan=2>"+unsafeWindow.ksoItems[C].name+"</td></tr>";
                    }
                }

            }

            m+='</TABLE><BR />';
        }

        if (rpt.marchName == ''+culang.mainReinforced+'') {
            m+=handleunts();
            m+=handlersc();
        }

        if (rpt.marchName == ''+culang.mainScout+'' && rslt['winner']==1) {
            m+='<TABLE class=pdxTab width=100%><TR><TD width=50% align=left valign=top>';
            m+=handleunts();
            if (rpt.side0TileTypeText!=''+culang.shortDarkForest+'')  m+=handlefrt();
            m+=handlersc();
            m+='</TD><TD width=50% align=left valign=top>';
            if (rpt.side0TileTypeText!=''+culang.shortDarkForest+'') {
                m+='<TABLE class=pdxTab width=100%>';
                if (rslt['lstlgn'] != undefined) {
                    if (!rslt['lstlgn'])
                        m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+': -</TD></TR>';
                    else
                        m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.lastlogin+': ' + formatUnixTime(rslt['lstlgn']) + '</TD></TR>';
                }
                m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+': ';
                if (rslt['knt'] != undefined)
                    m+=rslt['knt']['cbt'];
                else
                    m+=''+culang.mainNone+'';
                m+='</TD></TR>';

                if (rslt['pop'] != undefined)
                    m+='<TR><TD>'+uW.g_js_strings.commonstr.population+': ' + addCommas(rslt['pop']) + '</TD></TR>';
                if (rslt['hap'] != undefined)
                    m+='<TR><TD>'+uW.g_js_strings.commonstr.happiness+': ' + addCommas(rslt['hap']) + '</TD></TR></TABLE>';

                if (rslt['blds'] != undefined) {
                    m+='<b><a id=KsRptBatClick>'+uW.g_js_strings.commonstr.buildings+'</a></b><br><TABLE class=pdxTab id=KsRptBat style="display:none">';
                    for (var i=0; i<53; i++)
                        if (rslt['blds']['b'+i] != undefined)
                            m+=handleblds(i);
                    m+='</TABLE>';
                }
                if (rslt['tch'] != undefined) {
                    m+='<b><a id=KsRptRechercheClick>'+uW.g_js_strings.commonstr.technology+'</a></b><br><TABLE class=pdxTab id=KsRptRecherche style="display:none">';
                    for (var tl=1; tl < 17; tl++)
                        if (tl != 7)
                            m+='</TD></TR><TR><TD>'+researchLevels[tl].Name+'</TD><TD align=right>' + rslt['tch']['t'+tl] + '</TD></TR>';
                    m+='</TABLE>';
                }
            }
            //m+='</TD></TR></TABLE><br><input type=button value="'+culang.reportExportToCombat+'" id=KsExportCombat>';
            m+='</TD></TR></TABLE>';
        }

        if (rslt['fght'] != undefined){
            m+='<TABLE class=pdxTab width=100%><TR><TD width=50% align=left valign=top>';
            m+='<TABLE class=pdxTab width=100%>';
            m+='<TR><TD colspan=4><B>'+culang.mainAttacker+'</B> ('+rpt.side1Name+')';
            if (rslt['winner']==1)
                m+='<FONT color="#CC0000"><B> '+uW.g_js_strings.commonstr.winner+'</B></FONT>';
            m+='</TD></TR>';
            if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')
                m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+': ' + rslt['s1KCombatLv'] + '</TD></TR>';
            if (rslt['s1atkBoost']!== undefined)
                if (100*rslt['s1atkBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.attackboosted+': ' + 100*rslt['s1atkBoost'] + '%</TD></TR>';
            if (rslt['s1defBoost']!== undefined)
                if (100*rslt['s1defBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.defenseboosted+': ' + 100*rslt['s1defBoost'] + '%</TD></TR>';
            if (rslt['s1lifeBoost']!== undefined)
                if (100*rslt['s1lifeBoost']>0)
                    m+='<TR><TD colspan=4>Vie : ' + 100*rslt['s1lifeBoost'] + '%</TD></TR>';
            if (rslt['s1guardianDefBoost']!== undefined)
                if (100*rslt['s1guardianDefBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_defenseboosted+': ' + 100*rslt['s1guardianDefBoost'] + '%</TD></TR>';
            if (rslt['s1guardianAtkBoost']!== undefined)
                if ( 100*rslt['s1guardianAtkBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_attackboosted+': ' + 100*rslt['s1guardianAtkBoost'] + '%</TD></TR>';
            if (rslt['s1guardianMarchBoost']!== undefined)
                if (100*rslt['s1guardianMarchBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_marchboosted+': ' + 100*rslt['s1guardianMarchBoost'] + '%</TD></TR>';
            m+='<TR><TD colspan=4><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a> ' + rpt.side1CityName + '</TD></TR>';
            if (rslt['fght']["s1"] != undefined) {
                m+='<TR><TH></TH><TH align=left>'+uW.g_js_strings.commonstr.troops+'</TH><TH align=right>'+culang.reportFighted+'</TH><TH align=right>'+culang.reportSurvived+'</TH><TH align=right>'+culang.reportKilled+'</TH></TR>';
                for (var i=1;i<16;i++) {
                    if (rslt['fght']["s1"]['u'+i] != undefined) {
                        if (rslt['fght']["s1"]['u'+i][0] > rslt['fght']["s1"]['u'+i][1]) {
                            perte_atk= perte_atk +(rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1])*puipui[i-1];
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][0])+'</td>';
                            m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s1"]['u'+i][1])+'</FONT></td>';
                            m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s1"]['u'+i][0] - rslt['fght']["s1"]['u'+i][1])+'</FONT></td></tr>';
                        } else {
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][0])+'</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s1"]['u'+i][1])+'</td></tr>';
                        }
                    }
                }
            }
            m+='</TABLE><br>';
            // Bonus
            if (rslt['s1ThroneRoomBoosts']) {
                m+='<b><a id=KsRptS1ThroneClick>'+culang.reportShowThroneStuff+'</a></b><br><TABLE class=pdxTab id=KsRptS1Throne style="display:none">';
                for (var i in rslt['s1ThroneRoomBoosts']) {

                    m+='<TR><TD><B>'+uW.cm.thronestats.effects[i][1]+'</B></td><td align=right>'+ rslt['s1ThroneRoomBoosts'][i] +' %</td></tr>';

                }
                m+='</TABLE>';
            }else{
                m+='<b>'+culang.reportNoThroneStuff+'</b>';
            }

            m+='</TD><TD width=50% align=left valign=top>';
            m+='<TABLE class=pdxTab width=100%>';
            m+='<TR><TD colspan=4><B>'+culang.mainDefender+'</B> ('+rpt.side0Name+')';
            if (rslt['winner']==0)
                m+='<FONT color="#CC0000"><B> '+uW.g_js_strings.commonstr.winner+'</B></FONT>';
            m+='</TD></TR>';
            if (rpt.marchName == ''+culang.mainAttack+'' || rpt.marchName == ''+culang.mainDefense+'')
                m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.knightskills+': ' + rslt['s0KCombatLv'] + '</TD></TR>';
            if (rslt['s0atkBoost'] !== undefined)
                if (100*rslt['s0atkBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.attackboosted+': ' + 100*rslt['s0atkBoost'] + '%</TD></TR>';
            if (rslt['s0defBoost'] !== undefined)
                if (rslt['s0defBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.defenseboosted+': ' + 100*rslt['s0defBoost'] + '%</TD></TR>';
            if (rslt['s0lifeBoost']!== undefined)
                if (100*rslt['s0lifeBoost']>0)
                    m+='<TR><TD colspan=4>Vie : ' + 100*rslt['s0lifeBoost'] + '%</TD></TR>';
            if (rslt['s0guardianDefBoost']!== undefined)
                if (100*rslt['s0guardianDefBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_defenseboosted+': ' + 100*rslt['s0guardianDefBoost'] + '%</TD></TR>';
            if (rslt['s0guardianAtkBoost']!== undefined)
                if (100*rslt['s0guardianAtkBoost']>0)
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_attackboosted+': ' + 100*rslt['s0guardianAtkBoost'] + '%</TD></TR>';
            if (rslt['s0guardianMarchBoost']!== undefined)
                if (100*rslt['s0guardianMarchBoost'])
                    m+='<TR><TD colspan=4>'+uW.g_js_strings.modal_messages_viewreports_view.guardian_marchboosted+': ' + 100*rslt['s0guardianMarchBoost'] + '%</TD></TR>';
            if (rslt['rnds']!==undefined)
                m+='<TR><TD colspan=4>'+culang.mainRound+': ' + rslt['rnds'] + '</TD></TR>';
            if (rslt['fght']["s0"] != undefined) {
                m+='<TR><TH></TH><TH align=left>'+uW.g_js_strings.commonstr.troops+'</TH><TH align=right>'+culang.reportFighted+'</TH><TH align=right>'+culang.reportSurvived+'</TH></TR>';
                for (var i=1;i<16;i++) {
                    if (rslt['fght']["s0"]['u'+i] != undefined) {
                        if (rslt['fght']["s0"]['u'+i][0] > rslt['fght']["s0"]['u'+i][1]) {
                            perte_def= perte_def +(rslt['fght']["s0"]['u'+i][0] - rslt['fght']["s0"]['u'+i][1])*puipui[i-1];
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][0])+'</td>';
                            m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['u'+i][1])+'</FONT></td></tr>';
                        } else {
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][0])+'</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['u'+i][1])+'</td></tr>';
                        }
                    }
                }
                // Dark Forest
                for (var i=101;i<111;i++) {
                    if (rslt['fght']["s0"]['m'+i] != undefined) {
                        if (rslt['fght']["s0"]['m'+i][0] > rslt['fght']["s0"]['m'+i][1]) {
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][0])+'</td>';
                            m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['m'+i][1])+'</FONT></td></tr>';
                        } else {
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][0])+'</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['m'+i][1])+'</td></tr>';
                        }
                    }
                }
                //
                for (var i=53;i<=55;i++) {
                    if (rslt['fght']["s0"]['f'+i] != undefined) {
                        if (rslt['fght']["s0"]['f'+i][0] > rslt['fght']["s0"]['f'+i][1]) {
                            perte_def= perte_def +(rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1])*puipui[i];
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
                            m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</font></td></tr>';
                        } else {
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</td></tr>';
                        }
                    }
                }
                for (var i=60;i<=63;i++) {
                    if (rslt['fght']["s0"]['f'+i] != undefined) {
                        if (rslt['fght']["s0"]['f'+i][0] > rslt['fght']["s0"]['f'+i][1]) {
                            perte_def= perte_def +(rslt['fght']["s0"]['f'+i][0] - rslt['fght']["s0"]['f'+i][1])*puipui[i];
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
                            m+='<TD align=right><FONT color="#CC0000">'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</font></td></tr>';
                        } else {
                            m+='<TR><TD>' + unitImg[i] + '</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][0])+'</td>';
                            m+='<TD align=right>'+addCommas(rslt['fght']["s0"]['f'+i][1])+'</td></tr>';
                        }
                    }
                }
            } else
                m+='<TR><TD>'+uW.g_js_strings.modal_messages_viewreports_view.notroopsdef+'</TD></TR>';
            m+='</TABLE><br>';
            // Bonus divers ^^^
            if (rslt['s0ThroneRoomBoosts']) {
                m+='<b><a id=KsRptS0ThroneClick>'+culang.reportShowThroneStuff+'</a></b><br><TABLE class=pdxTab id=KsRptS0Throne style="display:none">';
                for (var i in rslt['s0ThroneRoomBoosts']) {

                    m+='<TR><TD><B>'+uW.cm.thronestats.effects[i][1]+'</B></td><td align=right>'+ rslt['s0ThroneRoomBoosts'][i] +' %</td></tr>';

                }

                m+='</TABLE>';

            }else{
                m+='<b>'+culang.reportNoThroneStuff+'</b>'
            }

            m+='</TD></TR>';
            delta_perte = perte_atk - perte_def;
            delta_pos = 1;
            ordre_grandeur = 1; //par defaut: perte en k
            delta_perte = delta_perte/1000;
            if (delta_perte<0){
                delta_pos = -1; //plus de perte pour def
                delta_perte = Math.abs(delta_perte);
            }
            if (delta_perte>1000) { //perte en Mega
                ordre_grandeur = 2;
                delta_perte = entier_1dec(delta_perte/1000);
            }
            if (delta_perte<1) { 
                ordre_grandeur = 0;
                delta_perte = entier_1dec(delta_perte*1000);
            }
            if (ordre_grandeur == 1) { //perte en kilo => garde 1chiffre apres virgule
                delta_perte = entier_1dec(delta_perte);
            }
            // transforme les pertes en kilo (avec 1 chiffre derriere virgule)
            perte_atk = entier_1dec(perte_atk/1000);
            perte_def = entier_1dec(perte_def/1000);

            m+='<TR><TD colspan=4>&nbsp;</TD></TR>';
            // affichage 
            if ((delta_pos == 1) && (delta_perte != 0)) {
                m+='<TR><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side1Name+') : </FONT><FONT color="#CC0000"> '+(perte_atk)+'k</FONT></TD><TD><FONT color="#00"><b>'+culang.reportMightLoose+'</b> ('+rpt.side0Name+') : '+perte_def+'k </FONT></TD></TR>';
                if (ordre_grandeur==2) {
                    m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'M</FONT></TD><TD></TD></TR></table>';
                } else if (ordre_grandeur==1){
                    m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'k </FONT></TD><TD></TD></TR></table>';
                } else if(ordre_grandeur==0){
                    m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'</FONT></TD><TD></TD></TR></table>';
                }
            }
            if ((delta_pos == -1) && (delta_perte != 0)) {
                m+='<TR><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side1Name+') : '+perte_atk+'k</FONT></TD><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side0Name+') : </FONT><FONT color="#CC0000"> '+perte_def+'k </FONT></TD></TR>';
                if (ordre_grandeur==2) {
                    m+='<TR><TD></TD><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'M</FONT></TD></TR></table>';
                } else if (ordre_grandeur==1){
                    m+='<TR><TD></TD><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'k</FONT></TD></TR></table>';
                } else if (ordre_grandeur==0){
                    m+='<TR><TD style="background-color: #FFFF00;"><FONT color="#ff00ff">'+culang.reportMightLooses+': </FONT><FONT color="#CC0000"> '+delta_perte+'</FONT></TD><TD></TD></TR></table>';
                }
            }
            if (delta_perte == 0 && (perte_def>0 || perte_atk>0)) {
                m+='<TR><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side1Name+'): '+perte_atk+'k</FONT></TD><TD><FONT color="#000"><b>'+culang.reportMightLoose+'</b> ('+rpt.side0Name+'): '+perte_def+'k </FONT></TD></TR></TABLE>';
            }
        }

        m+='</DIV>';
        t.popReport.getMainDiv().innerHTML = m;
        t.popReport.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.mainReport+'</DIV>';
        t.popReport.show(true);
        t.popReport.autoHeight (true);
        if (ById('KsRptS0ThroneClick')) {
            ById('KsRptS0ThroneClick').addEventListener('click', function () {
                if (ById('KsRptS0Throne').style.display=="none") {ById('KsRptS0Throne').style.display="block";} else {ById('KsRptS0Throne').style.display="none";}
            },false);
        }
        if (ById('KsRptS1ThroneClick')) {
            ById('KsRptS1ThroneClick').addEventListener('click', function () {
                if (ById('KsRptS1Throne').style.display=="none") {ById('KsRptS1Throne').style.display="block";} else {ById('KsRptS1Throne').style.display="none";}
            },false);
        }
        if (ById('KsRptBatClick')) {
            ById('KsRptBatClick').addEventListener('click', function () {
                if (ById('KsRptBat').style.display=="none") {ById('KsRptBat').style.display="block";} else {ById('KsRptBat').style.display="none";}
            },false);
        }
        if (ById('KsRptRechercheClick')) {
            ById('KsRptRechercheClick').addEventListener('click', function () {
                if (ById('KsRptRecherche').style.display=="none") {ById('KsRptRecherche').style.display="block";} else {ById('KsRptRecherche').style.display="none";}
            },false);
        }
        if (ById('KsExportCombat')) {
            ById('KsExportCombat').addEventListener('click', function () {
                if (rslt['unts'] != undefined) {
                    var A=0;
                    for(var troops in unsafeWindow.unitcost){
                        A++;
                        if (ById('pbcombatd_'+troops)) {
                            if  (rslt['unts']['u'+A] != undefined)
                                ById('pbcombatd_'+troops).value=rslt['unts']['u'+A];
                            else
                                ById('pbcombatd_'+troops).value=0;
                        }
                    }
                }
                // on remplit la technologie de la defenses
                if (rslt['tch'] != undefined) {
                    CombatOptions.research[0]['tch8']=rslt['tch']['t8'];
                    CombatOptions.research[0]['tch9']=rslt['tch']['t9'];
                    CombatOptions.research[0]['tch13']=rslt['tch']['t13'];
                    CombatOptions.research[0]['tch15']=rslt['tch']['t15'];
                }
                // chevalier
                if (rslt['knt'] != undefined) CombatOptions.knt[0] = rslt['knt']['cbt'];

                Tabs2.Combat.e_calculate();

                saveCombatOptions();

            }, false);


        }


    },

};
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Marches.js">
/************************************************************************************
 *                        KOC POWER - TABS MARCHES                                    *
 ************************************************************************************/
Tabs.Marches = {
    tabOrder: TabOptions.toMarches,
    tabLabel: culang.tabLabelMarch,
    cont:null,
    displayTimer:null,
    curTabBut : null,
    curTabName : null,
    state : null,

    hide : function (){
        var t = Tabs.Marches;
        clearTimeout (t.displayTimer);
    },

    show : function (){
        var t = Tabs.Marches;
        clearTimeout (t.displayTimer);
        if (t.curTabName == 'Z')
            t.showReinforcementsOut();
        else if (t.curTabName == 'R')
            t.showReinforcements();
        else if (t.curTabName == 'M')
            t.showMarches(9);
        else
            t.showAttacks();
    },
    init : function (div){
        var t = Tabs.Marches;
        t.cont = div;
        uW.pr58Recall = t.ajaxRecall;
        uW.Ksraid_delete = t.ajaxDeleteRaid;
        uW.r8x6Home = t.butSendHome;
        uW.pr57Recall = t.butRecall2;

        var atkclass='';
        if(Seed && Seed.queue_atkinc) {
            for(k in Seed.queue_atkinc){
                m = Seed.queue_atkinc[k];
                if (m.marchType == 4){
                    atkclass = 'style="background-color:#FF9999;"';
                }
            }
        }

        t.cont.innerHTML = '<TABLE class=pdxTab align=center><TR><TD><INPUT class=ksMSubtab ID=BoptmrchSubM type=submit value="'+ culang.mainMarches +'"></td>\
          <TD><INPUT class=ksMSubtab ID=BoptmrchSubA type=submit '+atkclass+' value="' + culang.marchIncommingButtonLabel + '"></td>\
          <TD><INPUT class=ksMSubtab ID=BoptmrchSubR type=submit value="'+culang.mainEmbassy+'"></td>\
          <TD><INPUT class=ksMSubtab ID=BoptmrchSubZ type=submit value="'+culang.mainReinforcement+'"></td><td><input type=button value="?" id=boaidemarches class=buttonHelp></td></tr></table>\
      <DIV id="BoptMarchOutput" style="margin-top:5px;max-height:'+(Options.HauteurBoite-65)+'px;overflow-y:auto"></div>';
        t.marchDiv = ById('BoptMarchOutput');
        ById('BoptmrchSubA').addEventListener('click', e_butSubtab, false);
        ById('BoptmrchSubR').addEventListener('click', e_butSubtab, false);
        ById('BoptmrchSubM').addEventListener('click', e_butSubtab, false);
        ById('BoptmrchSubZ').addEventListener('click', e_butSubtab, false);
        ById('boaidemarches').addEventListener('click', function(){
            window.open(homePage+" ");
        } , false);
        if (atkclass!='') {
            changeSubtab (ById('BoptmrchSubA'));
        }else {
            changeSubtab (ById('BoptmrchSubM'));
        }

        function e_butSubtab (evt){
            changeSubtab (evt.target);
        }

        function changeSubtab (but){
            if (but == t.curTabBut)
                return;
            if (t.curTabBut){
                t.curTabBut.className='ksMSubtab';
                t.curTabBut.disabled=false;
            }
            t.curTabBut = but;
            but.className='ksMSubtab ksMSubtabSel';
            but.disabled=true;
            t.curTabName = but.id.substr(11);
            if (Options.currentTab=="Marches") t.show2();
        }

    },
    show2 : function (){
        var t = Tabs.Marches;
        t.state = null;
        clearTimeout (t.displayTimer);
        if (t.curTabName == 'Z')
            t.showReinforcementsOut();
        else if (t.curTabName == 'R')
            t.showReinforcements();
        else if (t.curTabName == 'M')
            t.showMarches(9);
        else
            t.showAttacks();
    },

    /***   ATTACKS SUBTAB  ***/
    showAttacks : function (){
        var t = Tabs.Marches;
        clearTimeout (t.displayTimer);
        var now = unixTime();
        var target, atkType, who, atkclass;
        var ss = '<div class=pdxStat>'+culang.marchIncommingHead+' - <input type=button value="?" id=boaidemarches2 class=buttonHelp></div>';
        var s = '';
        s += '<STYLE> .eclkk{background:#ffff55;} .attackkk{background:#ff5555;} .attackkA{background:#ff9955;}</style>';
        s += '<TABLE border=0 cellspacing=0 cellpadding=2 width=100% class=pdxTab>';
        s += '<tr><td width=55><b><u>'+culang.mainArrival+'</u></b></td><td width=60><b><u>'+culang.mainDefense+'</u></b> </td><td width=140 colspan=2><b><u>'+culang.mainCastle+'</u></b></td><td width=150 colspan=2><b><u>'+culang.mainAttacker+'</u></b></td><td width=35><b><u>'+culang.mainDistance+ '</u></b></td><td width=25><b><u>'+culang.mainKnights+'</u></b></td><td><b><u>'+culang.mainTroops+'</u></b></td></tr>';
        var at=0;
        if(Seed && Seed.queue_atkinc) {
            var sortem = [];
            for (var k in Seed.queue_atkinc)
                sortem.push (Seed.queue_atkinc[k]);

            sortem.sort (function (a,b){
                var x; if ((x = a.arrivalTime-b.arrivalTime)!=0)
                    return x;
                return b.arrivalTime-a.arrivalTime;
            });

            for (i=0; i<sortem.length; i++){
                var m = sortem[i];

                if (m.marchType == 3){
                    atkType = culang.mainScouting;
                    atkclass = 'eclkk';
                } else if (m.marchType == 4){
                    atkType = uW.g_js_strings.commonstr.atk;
                    atkclass = 'attackkk';
                    var nbtroupe=0;
                    for (k in m.unts){
                        nbtroupe += parseInt(m.unts[k]);
                    }
                    if (nbtroupe==1) {
                        atkclass = 'attackkA';
                    }

                } else {
                    atkType ="?";
                    atkclass = '';
                }
                if (atkclass !='') {
                    at++;
                    s += '<tr align=left class="'+atkclass+'">';
                    var arrivedans = unsafeWindow.timestr(parseInt(m.arrivalTime - unixTime()));
                    s += '<td class="'+atkclass+'">' + arrivedans +'</td>';
                    var couelur="";
                    var city = Cities.byID[m.toCityId];
                    if (city.tileId == m.toTileId) {
                        target = '<a onclick="citysel_click(document.getElementById(\'citysel_'+ (city.idx+1)+'\'));">'+ city.name.substring(0,10) +'</a>';
                        cityID = 'city'+ m.toCityId;
                        Gate = parseInt(Seed.citystats[cityID].gate);
                        if(Gate == 0) {
                            bouttt = '<input type=button value="'+culang.mainHDef+' = '+culang.buttonOFF+'" id="but_'+m.toCityId+'" style="background-color:#00AA00;padding:2px;border:1px solid yellow;">';
                        }       else {
                            bouttt = '<input type=button value="'+culang.mainHDef+' = '+culang.buttonON+'" id="but_'+m.toCityId+'" style="background-color:red;">';
                        }
                        coordos = '<a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">('+ city.x + ',' + city.y +')</a>';
                    } else {
                        target = 'WILD';
                        bouttt='';
                        for (k in Seed.wilderness['city'+m.toCityId]){
                            if (Seed.wilderness['city'+m.toCityId][k].tileId == m.toTileId){
                                coordos = '<a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">('+Seed.wilderness['city'+m.toCityId][k].xCoord + ',' + Seed.wilderness['city'+m.toCityId][k].yCoord+')</a>';
                                break;
                            }
                        }
                    }
                    s += '<td class="'+atkclass+'" align=center>'+bouttt+'</td><td class="'+atkclass+'" align=center><b>' + target + '<td class="'+atkclass+'" align=center>'+coordos+'</b></td>';

                    if (Seed.players['u'+m.pid]) {
                        who = '<span>'+Seed.players['u'+m.pid].n +'<br>'+addCommas(Seed.players['u'+m.pid].m)+'</span>';

                    } else if (m.players && m.players['u'+m.pid]) {
                        who = m.players['u'+m.pid].n;
                    } else{
                        who = ''+culang.mainUnknown+'';

                    }
                    if (m.fromXCoord) {
                        who += '</td><td class="'+atkclass+'"><a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">(' + m.fromXCoord +','+ m.fromYCoord+')</a>';
                    } else {
                        who += '</td><td class="'+atkclass+'">???</a></td>';
                    }
                    s += '<td class="'+atkclass+'">' + who + '</td>';
                    if (m.fromXCoord) {
                        s +='<td class="'+atkclass+'">'+ distance(city.x,city.y,m.fromXCoord,m.fromYCoord) +'</td>';
                    } else {
                        s +='<td class="'+atkclass+'">&nbsp;</td>';
                    }
                    var troupe = "";
                    for (k in m.unts){
                        var uid = parseInt(k.substr (1));
                        troupe += m.unts[k] +' '+ unsafeWindow.unitcost['unt'+uid][0] +'<br>';
                    }
                    var knh='&nbsp;';
                    if (m.knt) {
                        for (k in m.knt){
                            knh=parseInt(m.knt[k]);
                        }
                    }
                    s += '<td class="'+atkclass+'">'+knh+'</td>';
                    s += '<td class="'+atkclass+'">' + troupe +'</td>';

                    s += '</tr>';
                }
            }
            s+='</table>';
            if (at==0) {
                s ="<tr><colspan=4><br><center><i><b>"+culang.marchIncommingHeadNoAttacks+"</b></i></center></td></tr>";
            }
        }
        t.marchDiv.innerHTML = ss + "" + s;
        ById('boaidemarches2').addEventListener('click', function(){
            window.open(homePage+" ");
        } , false);
        for (var cityId in Cities.byID){
            var but = document.getElementById ('but_'+ cityId);
            if (but) addListener (but, cityId);
        }
        function addListener (but, i){           but.addEventListener ('click', function (){t.butToggleDefMode(i)}, false);       }

        t.displayTimer = setTimeout (t.showAttacks, 900);
    },
    defMode:{},
    butToggleDefMode : function (cityId){
        var t = Tabs.Marches;
        var mode = 1;
        if (Seed.citystats["city" + cityId].gate != 0)
            mode = 0;
        t.ajaxSetDefMode (cityId, mode, function (newMode){

        });
    },
    ajaxSetDefMode : function (cityId, state, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = cityId;
        params.state = state;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/gate.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {
                    Seed.citystats["city" + cityId].gate = state;
                    notify (state);
                }
            },
            onFailure: function () {
            }
        })
    },

    /***   MARCHES SUBTAB  ***/
    showMarches : function (numville){

        var t = Tabs.Marches;
        var rownum = 0;
        var now = unixTime();
        var names = [''+culang.shrsupply+'', ''+culang.shrmilitiaman+'', ''+culang.scout+'', ''+culang.shrpikeman+'', ''+culang.shrswordsman+'', ''+culang.shrtarcher+'', ''+culang.shrcavalry+'', ''+culang.shrheavycavalry+'', ''+culang.shrsupplywagon+'', ''+culang.shrballista+'', ''+culang.shrbatteringram+'', ''+culang.shrcatapult+'', ''+culang.shrbloodthorn+'', ''+culang.shrexec+'', ''+culang.shrswall+'']; 
        clearTimeout (t.displayTimer);
        if (t.state == null){
            var s = '<div class=pdxStat>'+culang.marchHead+' <input type=button value="?" id=boaidemarches1 class=buttonHelp></div>';
            s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;}</style> <input style="font-size:12px" type=button id="9_KsVilleBouton" value="0">';
            for (var c=0; c<Cities.numCities; c++){
                s += '<input style="font-size:12px" type=button id="'+ c +'_KsVilleBouton" value="' + (parseInt(c)+1) + ': '+ Cities.cities[c].name.substring(0,10) +'">';
            }
            s += '<br><input id=KsVoirRaid type=checkbox '+ (!Options.voirRaid?'':' CHECKED ') +'> <b>'+culang.marchHideRaid+'</b> <div id="showMarchDiv"></div>';
            t.marchDiv.innerHTML = s;
            ById('boaidemarches1').addEventListener('click', function(){
                window.open(homePage+" ");
            } , false);
            ById('KsVoirRaid').addEventListener('click', function() {

                Options.voirRaid = ById('KsVoirRaid').checked;
                saveOptions();

            }, false);

            ById("9_KsVilleBouton").addEventListener('click', function(){
                var t = Tabs.Marches;
                clearTimeout (t.displayTimer);
                t.showMarches(this.id.substring(0,1));

            }, false);

            for (var c=0; c<Cities.numCities; c++){
                ById(c + "_KsVilleBouton").addEventListener('click', function(){
                    var t = Tabs.Marches;
                    clearTimeout (t.displayTimer);
                    t.showMarches(this.id.substring(0,1));
                }, false);
            }
            t.state = 1;
        }
        s = '<TABLE cellspacing=0 cellpadding=2 width=100% class=pdxTab>';
        tot = [];
        for (i=0; i<16; i++)  tot[i] = 0;
        var c = numville;
        if (numville==9) {
            for (var c=0; c<Cities.numCities; c++){
                var que = Seed.queue_atkp['city'+ Cities.cities[c].id];

                if (matTypeof(que)=='object') {
                    var a=0;
                    for (k in que) {
                        march = que[k];
                        if ((march.marchType!=2 && !Options.voirRaid) || (march.marchType!=9 && march.marchType!=2 && Options.voirRaid) ) {
                            a++;
                            if (a==1) {
                                var cityID = 'city'+ Cities.cities[c].id;
                                var rinfo = getRallypointInfo(Cities.cities[c].id);
                                var niveauPointRall = rinfo.maxMarches;
                                var slots = rinfo.usedSlots;
                                s+= '<TR class="city"><TD class="city">'+culang.mainSRallyPoint+': '+slots+' / '+niveauPointRall+'</td><TD class="city" colspan=19 align=center><font size=3><B><i><u>'+culang.mainCastle+' ' + (parseInt(c)+1) + ' - '+ Cities.cities[c].name +'</b></td></tr>';
                            }
                            var mid = k.substr(1);
                            knight = '';
                            if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
                                for (i in Seed.knights['city'+ Cities.cities[c].id]) {
                                    if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +'';
                                }
                            } else knight = '';
                            var playerId = march.toPlayerId;
                            if (playerId==undefined) playerId=0;
                            var cityId = march.toCityId;
                            var tileType = parseInt(march.toTileType);
                            var tileLevel = march.toTileLevel;
                            var who = ''+culang.mainUnknown+'';
                            if (Seed.players['u' + playerId]) {
                                who = Seed.players['u' + playerId].n;
                            }
                            if (march.marchType==1) {
                                var player = "<span>"+culang.mainCity+" "+ tileLevel +"</span>";
                            }else {
                                var player = "<span title='"+culang.reportBarbLevelNote+"'>"+culang.kocShortBarbarian+" "+ tileLevel +"</span>";
                            }
                            if (march.marchType==10 || march.marchType==11) {
                                var player = "<span>"+culang.shortDarkForest+": "+ tileLevel +"</span>";
                            }
                            var tileNames = [uW.g_js_strings.commonstr.barbarians, uW.g_js_strings.commonstr.grassland, uW.g_js_strings.commonstr.lake, uW.g_js_strings.commonstr.woods, uW.g_js_strings.commonstr.hills, uW.g_js_strings.commonstr.mountain, uW.g_js_strings.commonstr.plain, uW.g_js_strings.commonstr.city, uW.g_js_strings.commonstr.darkForest];
                            var numtile=parseInt(tileType/10) + 1;
                            if (tileType==10) numtile=1;
                            if (tileType==11) numtile=2;
                            if (tileType <= 50) {
                                player = tileNames[numtile] +" " + tileLevel;
                            }
                            if (tileType == 51 && playerId == 0 && march.toTileLevel==7) {
                                player = uW.g_js_strings.commonstr.city+" " + tileLevel;
                            }
                            if (tileType == 51 && playerId == 0 && march.toTileLevel==9) {
                                player = ""+culang.kocShortBarbarian+" " + tileLevel;
                            }
                            if (tileType == 54 && playerId == 0) {
                                player = ""+culang.shortDarkForest+": " + tileLevel;
                            }
                            var nomville="";
                            if (playerId > 0 && tileType == 51) {
                                if (march.marchType==1) {
                                    for(i=0; i<Cities.numCities; i++) {
                                        if (cityId==Cities.cities[i].id) {
                                            nomville=Cities.cities[i].name
                                            break;
                                        }
                                    }

                                    player = ''+culang.mainCastle+' '+ nomville;
                                } else {
                                    player = ''+culang.reportCityLevel+' ' + tileLevel;
                                }
                            }
                            var typeattack="?";
                            if (march.marchType==3) typeattack=culang.mainScouting;
                            if (march.marchType==4) typeattack=culang.mainAttack;
                            if (march.marchType==10) typeattack=culang.mainAttack;
                            if (march.marchType==11) typeattack=culang.mainScouting;
                            if (march.marchType==1) typeattack=culang.mainTransport;
                            if (march.marchType==5) typeattack=culang.mainReassign;
                            if (march.marchType==9) typeattack=culang.mainRaidAttack;
                            var now = new Date();
                            var statusm = march.marchStatus;
                            var Marchstatut="<span title='"+culang.mainType+": "+march.marchType+" "+culang.mainStatus+": "+statusm+"'>?</span> ";
                            var arrivedans="0s";
                            var arrivedanssec=0;
                            if (statusm==1) {
                                Marchstatut="";
                                if (march.marchType==3 || march.marchType==11)
                                    Marchstatut+='<img src="'+IMGmarchScouting+'" align=absmiddle>';
                                if (march.marchType==4 || march.marchType==10)
                                    Marchstatut+='<img src="'+IMGmarchAttacking+'" align=absmiddle>';
                                if (march.marchType==9)
                                    Marchstatut+='<img src="'+IMGmarchAttacking+'" align=absmiddle>';
                                if (march.marchType==1)
                                    Marchstatut+='<img src="'+IMGmarchTransporting+'" align=absmiddle>';
                                if (march.marchType==5)
                                    Marchstatut+='<img src="'+IMGmarchReinforce+'" align=absmiddle>';
                                Marchstatut+="&nbsp;"+uW.g_js_strings.commonstr.marching;
                                arrivedans = unsafeWindow.timestr(parseInt(march.destinationUnixTime - unixTime()));
                                arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
                            }
                            if (statusm==8) {
                                Marchstatut = '<img src="'+IMGmarchReturning+'" align=absmiddle>&nbsp;'+culang.mainReturn;
                                arrivedans = unsafeWindow.timestr(march.returnUnixTime - unixTime());
                                arrivedanssec = parseInt(march.returnUnixTime - unixTime());
                            }
                            if (statusm==2) {
                                Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+culang.mainCamped;
                            }
                            if (statusm==5) {
                                Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+uW.g_js_strings.attack_generatequeue.waitreport;
                            }
                            if (statusm==4) {
                                Marchstatut='<img src="'+IMGmarchRaidReset+'" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.unloadingloot;
                            }
                            if (statusm==3 || statusm==10 ) {
                                Marchstatut='<img src="'+IMGmarchRaidStoppedDesat+'" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.raidstopped;
                            }

                            s += '<TR align=left><td align=left width=10%>';
                            if (march.marchType!=9 && statusm==1 && arrivedanssec>60) s +='<A onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')" title="'+culang.marchRecallMarchNote+'"><SPAN><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
                            if (march.marchType!=9 && statusm==2) s +='<A onclick="attack_recall('+ mid+', 1, '+Cities.cities[c].id+');" title="'+culang.marchRecallAttackNote+'"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
                            if (march.marchType==9 && statusm==10 && arrivedanssec<=0) s +='<A onclick="Ksraid_delete('+ mid+','+Cities.cities[c].id+');return false;" title="'+culang.marchDeleteRaidNote+'"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></a>';

                            s +='</td><td align=left width=10%>'+typeattack+'</td><td>'+arrivedans+'</td><td align=left width=15%>' + Marchstatut +'</td>\
                <TD align=left width=15%>' + player + '</td><td><a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a></td><td>' + knight +' </td><td colspan=12>'
                            for (i=1; i<16; i++) {
                                if (statusm==8) {
                                    if (parseInt (march['unit'+ i +'Return']) > 0) {
                                        //s += unsafeWindow.unitcost['unt'+i][0].substr(0,6)+" :" + parseInt (march['unit'+ i +'Return']) + "<br>";
                                        s += names[i-1].substr(0,6)+" :" + parseInt (march['unit'+ i +'Return']) + "<br>";
                                        tot[i] += parseInt (march['unit'+ i +'Return']);
                                    }

                                } else {
                                    if (parseInt (march['unit'+ i +'Count']) > 0) {
                                        //s += unsafeWindow.unitcost['unt'+ i][0].substr(0,6) +" :" + parseInt (march['unit'+ i +'Count']) + "<br>";
                                        s += names[i-1].substr(0,6) +" :" + parseInt (march['unit'+ i +'Count']) + "<br>";
                                        tot[i] += parseInt (march['unit'+ i +'Count']);
                                    }
                                }
                            }

                            s += '</td><td style="font-size:11px">';
                            if (march.marchType!=9) {
                                s += '<a onclick="view_march('+ mid+');return false;"; title="'+culang.marchShowDetailsNote+'"><span><img  border=0 src="'+IMGshowButton+'"></span></a></td>';
                            }else {
                                s+='</td>';
                            }
                            s += '</tr>';
                        }
                    }
                }
            }
            s += '<TR><TD colspan=20><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100%><tr><td colspan=1></td>';
            for (var k=1;k<16;k++)
                //s += '<TD width=7% align=center><B>' + unsafeWindow.unitcost['unt'+k][0].substr(0,6) + '</b></td>';
                s += '<TD width=7% align=center><B>' + names[k-1].substr(0,6) + '</b></td>';
            s += '</tr>';
            s += '<TR align=center><TD class="tot" align=left width=10%><B>'+culang.mainHTotal+'</b></td>';
            for (i=1; i<16; i++)
                s+= '<TD class="tot">'+ tot[i] +'</td>';
            s += '<td></td></tr></table>';
            s += '<BR><BR><DIV style="font-size: 10px"></div>';

        } else {

            var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
            if (matTypeof(que)=='object') {
                var a=0;
                for (k in que){
                    march = que[k];

                    if ((march.marchType!=2 && !Options.voirRaid) || (march.marchType!=9 && march.marchType!=2 && Options.voirRaid) ) { 
                        a++;
                        if (a==1) {
                            var cityID = 'city'+ Cities.cities[c].id;
                            var rinfo = getRallypointInfo(Cities.cities[c].id);
                            var niveauPointRall = rinfo.maxMarches;
                            var slots = rinfo.usedSlots;
                            s+= '<TR class="city"><TD class="city">'+culang.mainSRallyPoint+': '+slots+' / '+niveauPointRall+'</td><TD class="city" colspan=18 align=center><font size=3><B><i><u>'+unsafeWindow.g_js_strings.commonstr.city+' ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
                        }
                        var mid = k.substr(1);
                        knight = '';
                        if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
                            for (i in Seed.knights['city'+ Cities.cities[c].id]) {
                                if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '&nbsp;('+culang.mainKnights+': ' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +')';
                            }
                        } else knight = '';
                        var playerId = march.toPlayerId;
                        if (playerId==undefined) playerId=0;
                        var cityId = march.toCityId;
                        var tileType = parseInt(march.toTileType);
                        var tileLevel = march.toTileLevel;
                        var who = ''+culang.mainUnknown+'';
                        if (Seed.players['u' + playerId]) {
                            who = Seed.players['u' + playerId].n;
                        }
                        if (march.marchType==1) { // si transport c'est forcement sur une ville lol
                            var player = "<span>"+culang.marchCityLevel+" "+ tileLevel +"</span>";
                        }else {
                            var player = "<span title='"+culang.reportBarbLevelNote+"'>"+culang.reportBarbLevel+" "+ tileLevel +"</span>";
                        }
                        if (march.marchType==10 || march.marchType==11) {
                            var player = "<span>"+culang.shortDarkForest+": "+culang.shortLevel+" "+ tileLevel +"</span>";
                        }
                        var tileNames = [uW.g_js_strings.commonstr.barbarians, uW.g_js_strings.commonstr.grassland, uW.g_js_strings.commonstr.lake, uW.g_js_strings.commonstr.woods, uW.g_js_strings.commonstr.hills,   uW.g_js_strings.commonstr.mountain,  uW.g_js_strings.commonstr.plain, uW.g_js_strings.commonstr.city, uW.g_js_strings.commonstr.darkForest];

                        var numtile=parseInt(tileType/10) + 1;
                        if (tileType==10) numtile=1;
                        if (tileType==11) numtile=2;
                        if (tileType <= 50) { // TS
                            player = tileNames[numtile] +" "+culang.shortLevel+" " + tileLevel;
                        }
                        if (tileType == 51 && playerId == 0 && march.toTileLevel==7) { // Ville
                            player = ""+culang.marchCityLevel+" " + tileLevel;
                        }
                        if (tileType == 51 && playerId == 0 && march.toTileLevel==9) { // Barbares
                            player = ""+culang.reportBarbLevel+" " + tileLevel;
                        }
                        if (tileType == 54 && playerId == 0) { // Barbares
                            player = ""+culang.shortDarkForest+": "+culang.shortLevel+" " + tileLevel;
                        }
                        var nomville="";
                        if (playerId > 0 && tileType == 51) { // ville
                            if (march.marchType==1) {
                                for(i=0; i<Cities.numCities; i++) {
                                    if (cityId==Cities.cities[i].id) {
                                        nomville=Cities.cities[i].name
                                        break;
                                    }
                                }
                                player = ''+culang.mainCity+' '+ nomville;
                            } else {
                                player = ''+culang.reportCityLevel+' ' + tileLevel;
                            }
                        }
                        var typeattack="?";



                        if (march.marchType==3) typeattack=culang.mainScouting;
                        if (march.marchType==4) typeattack=culang.mainAttack;
                        if (march.marchType==10) typeattack=culang.mainAttack;
                        if (march.marchType==11) typeattack=culang.mainScouting;
                        if (march.marchType==1) typeattack=culang.mainTransport;
                        if (march.marchType==5) typeattack=culang.mainReassign;
                        if (march.marchType==9) typeattack=culang.mainRaidAttack;
                        var now = new Date();
                        var statusm = march.marchStatus;
                        var Marchstatut="<span title='"+culang.mainType+": "+march.marchType+" "+culang.mainStatus+": "+statusm+"'>?</span> ";
                        var arrivedans="0s";
                        var arrivedanssec=0;
                        if (statusm==1) {
                            Marchstatut="";
                            if (march.marchType==3 || march.marchType==11)
                                Marchstatut+='<img src="'+IMGmarchScouting+'" align=absmiddle>';
                            if (march.marchType==4 || march.marchType==10)
                                Marchstatut+='<img src="'+IMGmarchAttacking+'" align=absmiddle>';
                            if (march.marchType==9)
                                Marchstatut+='<img src="'+IMGmarchAttacking+'" align=absmiddle>';
                            if (march.marchType==1)
                                Marchstatut+='<img src="'+IMGmarchTransporting+'" align=absmiddle>';
                            if (march.marchType==5)
                                Marchstatut+='<img src="'+IMGmarchReinforce+'" align=absmiddle>';
                            Marchstatut+="&nbsp;"+uW.g_js_strings.commonstr.marching;
                            arrivedans = unsafeWindow.timestr(parseInt(march.destinationUnixTime - unixTime()));
                            arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
                        }
                        if (statusm==8) {
                            Marchstatut = '<img src="'+IMGmarchReturning+'" align=absmiddle>&nbsp;'+culang.mainReturn;
                            arrivedans = unsafeWindow.timestr(march.returnUnixTime - unixTime());
                            arrivedanssec = parseInt(march.returnUnixTime - unixTime());
                        }
                        if (statusm==2) {
                            Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+culang.mainCamped;
                        }
                        if (statusm==5) {
                            Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+uW.g_js_strings.attack_generatequeue.waitreport;
                        }
                        if (statusm==4) {
                            Marchstatut='<img src="'+IMGmarchRaidReset+'" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.unloadingloot;
                        }
                        if (statusm==3 || statusm==10) {
                            Marchstatut='<img src="'+IMGmarchRaidStoppedDesat+'" align=absmiddle>&nbsp;' + uW.g_js_strings.attack_generatequeue.raidstopped;
                        }

                        s += '<TR align=left><td align=left width=10%>';
                        if (march.marchType!=9 && statusm==1 && arrivedanssec>60) s +='<A onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')"><SPAN><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
                        if (march.marchType!=9 && statusm==2) s +='<A onclick="attack_recall('+ mid+', 1, '+Cities.cities[c].id+');"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
                        if (march.marchType==9 && statusm==10 && arrivedanssec<=0) s +='<A onclick="Ksraid_delete('+ mid+','+Cities.cities[c].id+');return false;"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></a>';

                        s +='</td><td align=left width=10%>'+typeattack+'</td><td>'+arrivedans+'</td><td align=left width=15%>' + Marchstatut +'</td>\
                          <TD align=left width=15%>' + player + '</td><td><a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a></td><td>' + knight +' </td><td colspan=12>'
                        for (i=1; i<16; i++) {
                            if (statusm==8) {
                                if (parseInt (march['unit'+ i +'Return']) > 0) {
                                    s += names[i-1]+" :" + parseInt (march['unit'+ i +'Return']) + "<br>";
                                    tot[i] += parseInt (march['unit'+ i +'Return']);
                                }

                            } else {
                                if (parseInt (march['unit'+ i +'Count']) > 0) {
                                    s += names[i-1]+" :" + parseInt (march['unit'+ i +'Count']) + "<br>";
                                    tot[i] += parseInt (march['unit'+ i +'Count']);
                                }
                            }
                        }

                        s += '</td><td style="font-size:11px">';
                        if (march.marchType!=9) {
                            s += '<a  onclick="view_march('+ mid+');return false;"; title="'+culang.marchShowDetailsNote+'"><span><img border=0 src="'+IMGshowButton+'"></span></a></td>';
                        }else {
                            s+='</td>';
                        }
                        s += '</tr>';
                    }// fin de MarchType
                } // fin k in que
                s += '<TR><TD colspan=19><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100% class=pdxTab ><tr><td colspan=1></td>';
                for (k=0; k<names.length; k++)  s += '<TD width=7% align=center><B>' + names[k] + '</b></td>';
                s += '</tr>';
                s += '<TR align=center><TD class="tot" align=left width=10%><B>'+culang.mainHTotal+'</b></td>';
                for (i=1; i<16; i++) s+= '<TD class="tot">'+ tot[i] +'</td>';
                s += '<td></td></tr></table>';
            } else {
                s= '<br><center><b><i>'+culang.marchNoMarches+'</i></b></center>';
            }
        } // Fin c=99
        ById('showMarchDiv').innerHTML = s;
        t.displayTimer = setTimeout (function() { t.showMarches(numville);   }, 1000);
    },
    ajaxDeleteRaid: function(marchId, cityId) {
        var villeencours=cityId;
        var march = Seed.queue_atkp["city" + villeencours]["m" + marchId];
        if (march == null){
            return;
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.action="deleteMarch";
        params.marchId = marchId;
        params.ctrl="BotManager";
        params.settings={cityId:villeencours};
        unsafeWindow.ajax.Request(unsafeWindow.g_ajaxpath+"ajax/_dispatch.php"+unsafeWindow.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
            onSuccess:function(transport) {
                var m = eval("(" + transport.responseText + ")");
                if (m.ok){
                    var j=marchId;
                    var t=cityId;
                    var n=Seed.units["city"+t];
                    for(var o=0;o<16;++o){
                        if (m["unit"+o+"Return"]) {
                            var p=parseInt(m["unit"+o+"Return"]);
                            if(!isNaN(p)&&(p>0)){
                                n["unt"+o]=parseInt(n["unt"+o])+p;
                            }
                        }
                    }
                    unsafeWindow.cityinfo_army();
                    var s="city"+t;
                    // recherche de mon chevalier
                    var mymarch = unsafeWindow.seed.queue_atkp["city" + t]["m" + j];
                    var kngId= mymarch.knightId;
                    delete Seed.queue_atkp[s]["m"+j];
                    if(unsafeWindow.Object.keys(Seed.queue_atkp[s]).length==0){
                        Seed.queue_atkp[s]=[];
                    }
                    Seed.knights["city"+t]["knt"+kngId].knightStatus=1;
                } else {


                }
            }, onFailure: function () {

            },
        });

    },
    /***  REINFORCEMENTS SUBTAB  ***/
    showReinforcementsOut : function (){
        var rownum = 0;
        var names = [''+culang.shrsupply+'', ''+culang.shrmilitiaman+'', ''+culang.scout+'', ''+culang.shrpikeman+'', ''+culang.shrswordsman+'', ''+culang.shrtarcher+'', ''+culang.shrcavalry+'', ''+culang.shrheavycavalry+'', ''+culang.shrsupplywagon+'', ''+culang.shrballista+'', ''+culang.shrbatteringram+'', ''+culang.shrcatapult+'', ''+culang.shrbloodthorn+'', ''+culang.shrexec+'', ''+culang.shrswall+'']; 
        var t = Tabs.Marches;
        clearTimeout (t.displayTimer);
        var s = '<div class=pdxStat>'+culang.marchReinforcementHead+' - <input type=button value="?" id=boaidemarches4 class=buttonHelp></div>';
        s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;}</style>';
        s += '<TABLE cellspacing=0 cellpadding=2 width=100% class=pdxTab >';
        tot = [];
        for (i=0; i<16; i++)
            tot[i] = 0;

        for (var c=0; c<Cities.numCities; c++){
            var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
            if (matTypeof(que)=='array')
                continue;

            var a=0;
            for (k in que){
                march = que[k];
                if (march.marchType==2) {
                    a++;
                    if (a==1) {
                        s+= '<TR class="city"><TD class="city" colspan=16 align=left><B>'+culang.mainCastle+' ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
                    }
                    var mid = k.substr(1);
                    knight = '';
                    if (Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"] !=0){
                        for (i in Seed.knights['city'+ Cities.cities[c].id]) {
                            if (i == ("knt" + Seed.queue_atkp['city'+ Cities.cities[c].id][k]["knightId"]) ) knight = '' +Seed.knights['city'+ Cities.cities[c].id][i]["combat"] +'';
                        }
                    } else knight = '';
                    if (parseInt(march.knightCombat)>0) knight=' ('+ march.knightCombat +')';
                    try {
                        player = Seed.players['u'+march.toPlayerId].n; //Seed.players['u'+k].n;
                    } catch (err){
                        player = ''+culang.mainUnknown+'';
                    }

                    s += '<TR align=left><td align=left width=12%>';
                    var statusm = march.marchStatus;
                    var Marchstatut='';
                    var arrivedans="0s";
                    var arrivedanssec=0;
                    if (statusm==1) {
                        Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+uW.g_js_strings.commonstr.marching;
                        arrivedans = unsafeWindow.timestr(parseInt(march.destinationUnixTime - unixTime()));
                        arrivedanssec = parseInt(march.destinationUnixTime - unixTime());
                    }
                    if (statusm==2) {
                        Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+culang.mainCamped;
                    }
                    if (statusm==8) {
                        Marchstatut='<img src="'+IMGmarchReturning+'" align=absmiddle>&nbsp;'+culang.mainReturn;
                        arrivedans = unsafeWindow.timestr(parseInt(march.returnUnixTime - unixTime()));
                        arrivedanssec = parseInt(march.returnUnixTime - unixTime());
                    }
                    if (statusm==5) {
                        Marchstatut='<img src="'+IMGmarchReinforce+'" align=absmiddle>&nbsp;'+uW.g_js_strings.attack_generatequeue.waitreport;
                    }
                    if (statusm==1 && arrivedanssec>60){
                        s +='<A onclick="pr58Recall('+ mid+','+Cities.cities[c].id+')" title="'+culang.marchReinforcementRecallTroopsNowNote+'"><SPAN><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
                    }
                    if (statusm==2) {
                        s +='<A onclick="pr57Recall('+ mid+')"  title="'+culang.marchReinforcementRecallTroopsNowNote+'"><SPAN><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainRecall+'" alt="'+culang.mainRecall+'"></span></a>';
                    } else {
                        s += '&nbsp;';
                    }

                    s+='</td><td align=left width=15%>'+Marchstatut+'</td><td>'+arrivedans+'</td><TD align=left width=30%>' + player + ' <a class="coordinateLink" onclick="cm.utils.CoordinateLinkController.onClick(event)" href="javascript:void(0)">(' + march.toXCoord +','+ march.toYCoord +')</a>&nbsp;' + knight +' </td><td colspan=12>'
                    for (i=1; i<16; i++) {
                        if (statusm==8) {
                            if (parseInt (march['unit'+ i +'Return']) > 0) {
                                s += " " + parseInt (march['unit'+ i +'Return']) + " "+names[i-1]+"<br>";
                                tot[i] += parseInt (march['unit'+ i +'Return']);
                            }

                        } else {
                            if (parseInt (march['unit'+ i +'Count']) > 0) {
                                s += " " + parseInt (march['unit'+ i +'Count']) + " "+names[i-1]+"<br>";
                                tot[i] += parseInt (march['unit'+ i +'Count']);
                            }
                        }
                    }
                    s += '</td></tr>';
                }// fin de MarchType
            }
        }

        s += '<TR><TD colspan=18><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 class=pdxTab width=100%><tr><td colspan=1></td>';
        for (k=0; k<names.length; k++)
            s += '<TD width=7% align=center><B>' + names[k] + '</b></td>';
        s += '</tr>';
        s += '<TR align=center><TD class="tot" align=left width=10%><B>'+culang.mainHTotal+'</b></td>';
        for (i=1; i<16; i++)
            s+= '<TD class="tot">'+ tot[i] +'</td>';
        s += '</tr></table>';
        t.marchDiv.innerHTML = s;
        ById('boaidemarches4').addEventListener('click', function(){
            window.open(homePage+" ");
        } , false);
        t.displayTimer = setTimeout (t.showReinforcementsOut, 5000);
        return;
    },

    showReinforcements : function (){
        var rownum = 0;
        var names = [''+culang.shrsupply+'', ''+culang.shrmilitiaman+'', ''+culang.scout+'', ''+culang.shrpikeman+'', ''+culang.shrswordsman+'', ''+culang.shrtarcher+'', ''+culang.shrcavalry+'', ''+culang.shrheavycavalry+'', ''+culang.shrsupplywagon+'', ''+culang.shrballista+'', ''+culang.shrbatteringram+'', ''+culang.shrcatapult+'', ''+culang.shrbloodthorn+'', ''+culang.shrexec+'', ''+culang.shrswall+'']; 
        var t = Tabs.Marches;
        clearTimeout (t.displayTimer);

        function clickShowRemaining (){
            checkBox = ById('idCheck2');
            if (checkBox.checked)
                Options.encRemaining = false;
            else
                Options.encRemaining = true;
            t.show2 ();
        }

        enc = {};
        numSlots = 0;

        if (matTypeof(Seed.queue_atkinc) != 'array'){
            for (k in Seed.queue_atkinc){
                march = Seed.queue_atkinc[k];
                if (march.marchType == 2){
                    ++numSlots;
                    city = march.toCityId;
                    from = march.fromPlayerId;
                    if (!enc[city])
                        enc[city] = {};
                    if (!enc[city][from])
                        enc[city][from] = [];
                    s = {};
                    s.knight = parseInt (march.knightCombat);
                    s.marchId = k.substr(1);
                    s.fromXCoord = march.fromXCoord;
                    s.fromYCoord = march.fromYCoord;
                    s.troops = [];
                    for (i=1; i<16; i++){
                        if (Options.encRemaining)
                            s.troops[i] = parseInt (march['unit'+ i +'Return']);
                        else
                            s.troops[i] = parseInt (march['unit'+ i +'Count']);
                    }
                    enc[city][from].push (s);
                }
            }
        }
        s = '<div class=pdxStat>'+culang.marchEmbassyHead+' - <input type=button value="?" id=boaidemarches3 class=buttonHelp></div>';
        if (numSlots == 0){
            s += '<BR><CENTER><B><i>'+culang.marchEmbassyNoTroops+'</i></b></center>';
        } else {
            s += '<STYLE> .tot{background:#f0e0f8;} .city{background:#ffffaa;} .entete{background:#efa9a9;}</style>';
            s += '<TABLE cellspacing=0 cellpadding=2 width=100%>\
      <tr><td class="entete"><u><b>'+culang.mainAction+'</b></u></td><td class="entete"><u><b>'+culang.mainCoordinate+'</b></u></td><td class="entete"><u><b>'+culang.marchEmbassyFromPlayer+'</b></u></td><td class="entete"><u><b>'+culang.mainKnights+'</b></u></td><td colspan=12 class="entete"><u><b>'+culang.mainTroops+'</b></u></td><td class="entete"><u><b>'+culang.marchEmbassyShortFoodUsage+'</b></u></td></tr>';

            tot = [];
            totent= 0;
            for (i=0; i<16; i++) {
                tot[i] = 0;

            }
            for (c in Cities.cities){
                dest = Cities.cities[c].id;
                if (enc[dest]){
                    s+= '<TR><TD class="city" colspan=18 align=left><B>'+culang.mainCastle+' - ' + (parseInt(c)+1) + ' : '+ Cities.cities[c].name +'</b></td></tr>';
                    for (p in enc[dest]){
                        try {
                            player = Seed.players['u'+p].n;
                        } catch (err){
                            player = '???';
                        }
                        for (m=0; m<enc[dest][p].length; m++){
                            var march = enc[dest][p][m];
                            knight = '';
                            if (march.knight > 0)
                                knight = ' '+ march.knight +'';
                            s += '<TR align=left><td align=left width=12%><A onclick="r8x6Home('+ march.marchId +')" title="'+culang.marchEmbassySendHomeNote+'"><SPAN><img src="'+IMGdeleteButton+'"></span></a></td>\
              <TD align=left><a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+march.fromXCoord+','+march.fromYCoord+')'+'</a></td>\
              <TD align=left width=25%>'+ player +' </td><td align=left>'+ knight+'</td><td colspan=12>'
                            var g=0;
                            for (i=1; i<16; i++){
                                if (march.troops[i] > 0) {
                                    s += ''+ march.troops[i]  +' '+ names[i-1]  +'<br>';
                                }
                                tot[i] += march.troops[i];
                                g+=parseInt(march.troops[i])*parseInt(unsafeWindow.unitupkeeps[i]);

                            }
                            totent += g;
                            s += '</td><td>';
                            s += addCommas(g) + '</td></tr>';
                        }
                    }
                }
            }
            s += '<TR><TD colspan=18><BR><BR></td></tr></table><TABLE cellspacing=0 cellpadding=2 width=100%><tr><td colspan=1></td>';
            for (k=0; k<names.length; k++)
                s += '<TD width=7% align=center><B>' + names[k] + '</b></td>';
            s += '</tr>';
            s += '<TR align=center><TD class="tot" align=left width=10% rowspan=2><B>'+culang.mainHTotal+'</b></td>';
            for (i=1; i<16; i++)
                s+= '<TD class="tot">'+ tot[i] +'</td>';
            s += '</tr><td colspan=12><span class="boldRed">'+culang.marchEmbassyFoodUsage+'</span>: '+addCommas(totent)+' '+unsafeWindow.g_js_strings.commonstr.food+'/'+culang.shortHour+'</td></table>';
        }

        s += '<BR><INPUT type=CHECKBOX id=idCheck2 '+ (Options.encRemaining?'':' CHECKED ') +'> '+culang.marchEmbassyShowOriginalTroops+'';
        s += '<BR><sup><span class="boldRed">'+culang.mainImportant+'</span>:</sup> <span class="helpText">'+culang.marchEmbassyShowOriginalTroopsNote+'</span></div>';
        t.marchDiv.innerHTML = s;
        checkBox = ById('idCheck2');
        ById('boaidemarches3').addEventListener('click', function(){  window.open(homePage+" ");    } , false);
        checkBox.addEventListener('click', clickShowRemaining, false);
        t.displayTimer = setTimeout (t.show2, 10000);
    },
    butSendHome : function (marchId){
        var t = Tabs.Marches;
        t.ajaxSendHome (marchId);
    },
    ajaxSendHome : function (marchId, notify){
        var march = Seed.queue_atkinc['m'+ marchId];
        if (march == null)
            return;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.mid = marchId;
        params.cid = march.toCityId;
        params.fromUid = march.fromPlayerId;
        params.fromCid = march.fromCityId;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/kickoutReinforcements.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok){
                    var upkeep = 0;
                    for (var i=1; i<16; i++)
                        upkeep += parseInt(march["unit" + i + "Return"]) * parseInt(unsafeWindow.unitupkeeps[i]);
                    unsafeWindow.seed.resources["city"+ march.toCityId].rec1[3] -= upkeep;
                    if (parseInt(march.fromPlayerId) == parseInt(unsafeWindow.tvuid)) {
                        var mymarch = unsafeWindow.seed.queue_atkp["city" + march.fromCityId]["m" + marchId];
                        var marchtime = Math.abs(parseInt(mymarch.destinationUnixTime) - parseInt(mymarch.eventUnixTime));
                        mymarch.returnUnixTime = unixTime() + marchtime;
                        mymarch.marchStatus = 8;
                    }
                    delete unsafeWindow.seed.queue_atkinc["m" + marchId];
                    if (notify != null)
                        notify(null);
                } else {
                    if (notify != null)
                        notify(rslt.errorMsg);
                }
            },
            onFailure: function () {
                if (notify != null)
                    notify(rslt.errorMsg);
            },
        });
    },
    butRecall2 : function (marchId){
        var t = Tabs.Marches;
        t.ajaxRecall2 (marchId);
    },
    ajaxRecall2 : function (marchId, notify){
        var villeencours;
        for (var c=0; c<Cities.numCities; c++){
            var que = Seed.queue_atkp['city'+ Cities.cities[c].id];
            if (matTypeof(que)=='array')
                continue;
            for (k in que){
                if (k == 'm'+marchId){
                    villeencours = Cities.cities[c].id;
                    break;
                }
            }
        }
        var march = Seed.queue_atkp["city" + villeencours]["m" + marchId];
        if (march == null){
            return;
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.mid = marchId;
        params.cid = villeencours;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/undefend.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok){
                    if(rslt.updateSeed){
                        unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].marchStatus=8;
                        var marchtime=parseInt(unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].returnUnixTime)-parseInt(unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].destinationUnixTime);
                        var ut=unsafeWindow.unixtime();
                        if(unsafeWindow.seed.playerEffects.returnExpire>ut){marchtime*=0.5}
                        unsafeWindow.seed.queue_atkp["city"+villeencours]["m"+marchId].destinationUnixTime=rslt.destinationUnixTime||ut;
                        unsafeWindow.seed.queue_atkp["city"+villeencours]["m"+marchId].returnUnixTime=rslt.returnUnixTime||ut+marchtime*rslt.returnMultiplier;
                        unsafeWindow.seed.queue_atkp["city"+villeencours]["m"+marchId].marchStatus=8;
                        unsafeWindow.update_seed(rslt.updateSeed)
                    }
                }
            },
            onFailure: function () {
            },
        });

    },
    ajaxRecall : function (marchId, cid, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.mid = marchId;
        params.cid = cid;

        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelMarch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok){

                    if(rslt.updateSeed){
                        unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].marchStatus=8;
                        var marchtime=parseInt(unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].returnUnixTime)-parseInt(unsafeWindow.seed.queue_atkp["city"+params.cid]["m"+params.mid].destinationUnixTime);
                        var ut=unsafeWindow.unixtime();
                        if(unsafeWindow.seed.playerEffects.returnExpire>unsafeWindow.unixtime()){marchtime*=0.5}
                        unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId].destinationUnixTime=rslt.destinationUnixTime||ut;
                        unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId].returnUnixTime=rslt.returnUnixTime||ut+marchtime*rslt.returnMultiplier;
                        unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId].marchStatus=8;
                        unsafeWindow.update_seed(rslt.updateSeed);
                    }
                    for(var j=1;j<16;j++){
                        unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId]["unit"+j+"Return"]=parseInt(unsafeWindow.seed.queue_atkp["city"+cid]["m"+marchId]["unit"+j+"Count"])
                    }
                }
            },
            onFailure: function () {
            },
        });

    },
};
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Search.js">
/************************************************************************************
 *                        KOC POWER - TABS SEARCH                                        *
 ************************************************************************************/
Tabs.Search = {
    tabOrder: TabOptions.toSearch,
    tabLabel: culang.tabLabelSearch,
    cont:null,
    state : null,
    show : function (div){
        var t = Tabs.Search;
    },
    hide : function (){
    },
    clickedPlayerDetail : function (span, uid){
        var t = Tabs.AllianceList;
        span.onclick = '';
        span.innerHTML = ""+culang.searchPlayerDetails+"";
        t.fetchPlayerInfo (uid, function (r) {t.gotPlayerDetail(r, span)});
    },
    clickedPlayerLeaderboard : function (span, uid){
        var t = Tabs.AllianceList;
        span.onclick = '';
        span.innerHTML = "<i><b>"+culang.searchPlayerLeaderboard+"</b></i>";
        t.fetchLeaderboard (uid, function (r) {t.gotPlayerLeaderboard(r, span)});
    },
    gotPlayerLeaderboard : function (rslt, span){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            span.innerHTML = rslt.errorMsg;
            return;
        }
        if (rslt.totalResults == 0){
            span.innerHTML = "<B></b>"+culang.mainError+": "+culang.searchNotFoundInMist+"";
            return;
        }
        var p = rslt.results[0];
        var an = p.allianceName;
        if (!an || an=='' || p.officerType==4)
            an = 'Aucun';
        else
            an += ' ('+ officerId2String(p.officerType) +')';
        m = '<TABLE cellspacing=0 class=pdxTab><TR><TD><B>'+culang.mainCastle+': </b></td><TD colspan=2> '+uW.g_js_strings.commonstr.might+': '+ p.might  +' &nbsp; '+uW.g_js_strings.commonstr.alliance+': '+ an +'</td></tr>';
        for (var i=0; i<p.cities.length; i++){
            var c = p.cities[i];
            m += '<TR><TD align=right><B>'+culang.mainCity+' #'+ (i+1) +':</b></td><TD> &nbsp; '+ c.cityName
                +' <a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ c.xCoord +',' +c.yCoord+ ')</a></td><TD width=75%> &nbsp; '+uW.g_js_strings.commonstr.level+': '
                + c.tileLevel +' &nbsp; &nbsp; status: '+ cityStatusString (c.cityStatus) +' &nbsp; &nbsp; '+culang.searchPlayerCreate+' ' + c.dateCreated.substr(0,10) +'</td></tr>';
        }
        span.innerHTML = m + '</table>';
    },
    gotPlayerDetail : function (rslt, span){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            span.innerHTML = rslt.errorMsg;
            return;
        }
        var u = rslt.userInfo[0];
        var a = 'Aucun';
        if (u.allianceName)
            a = u.allianceName +' ('+ getDiplomacy(u.allianceId) + ')';
        var m = '<TABLE cellspacing=0 class=pdxTab><TR><TD><B>'+culang.searchDetails+':</b> &nbsp; </td><TD>'+uW.g_js_strings.commonstr.alliance+': '+ a +' &nbsp; '+culang.mainCities+': '
            + u.cities +' &nbsp; '+culang.mainPopulation+': '+ u.population +'</td></tr><TR><TD></td><TD>'+culang.mainProvinces+': ';
        var pids = u.provinceIds.split (',');
        var p = [];
        for (var i=0; i<pids.length; i++)
            p.push(unsafeWindow.provincenames['p'+pids[i]]);
        span.innerHTML = m + p.join (', ') +'</td></tr></table>';
    },

    aName : '',
    eventSubmit : function (){
        var t = Tabs.AllianceList;
        ById('ptallErr').innerHTML='';
        t.aName = ById('allAllName').value;
        if (t.aName.length < 3){
            ById('ptallErr').innerHTML = ''+culang.searchMin3Letter+'';
            return;
        }
        var myA = getMyAlliance ();
        ById('altInput').innerHTML = '';
        ById('allListOut').innerHTML = '<BR><center><b><i>'+culang.searchPlayerLeaderboard+'</i></b></center>';
        if (myA[0]!=0 && myA[1].toLowerCase().indexOf(t.aName.toLowerCase())>=0 )
            t.fetchAllianceList (t.aName, myA[0], t.eventGotAllianceList);
        else
            t.fetchAllianceList (t.aName, null, t.eventGotAllianceList);
    },
    init : function (div){
        var t = Tabs.Search;
        this.cont = div;
        uW.BoPTpd = t.clickedPlayerDetail;
        uW.BoPTpd2 = t.clickedPlayerLeaderboard;
        uW.BoPCpo2 = t.clickedPlayerCheckOnline;
        uW.BoPCplo2 = t.clickedPlayerGetLastLogin;
        var Provinces={1:{name:uW.provincenames["p1"],x:75,y:75},2:{name:uW.provincenames["p2"],x:225,y:75},3:{name:uW.provincenames["p3"],x:375,y:75},4:{name:uW.provincenames["p4"],x:525,y:75},5:{name:uW.provincenames["p5"],x:675,y:75},6:{name:"Paimpont",x:75,y:225},7:{name:"Cameliard",x:225,y:225},8:{name:"Sarras",x:375,y:225},9:{name:"Canoel",x:525,y:225},10:{name:"Avalon",x:675,y:225},11:{name:"Carmathen",x:75,y:375},12:{name:"Shallot",x:225,y:375},13:{name:"-------",x:375,y:375},14:{name:uW.provincenames["p13"],x:525,y:375},15:{name:uW.provincenames["p14"],x:675,y:375},16:{name:uW.provincenames["p15"],x:75,y:525},17:{name:uW.provincenames["p16"],x:225,y:525},18:{name:uW.provincenames["p17"],x:375,y:525},19:{name:uW.provincenames["p18"],x:525,y:525},20:{name:uW.provincenames["p19"],x:675,y:525},21:{name:uW.provincenames["p20"],x:75,y:675},22:{name:uW.provincenames["p21"],x:225,y:675},23:{name:uW.provincenames["p22"],x:375,y:675},24:{name:uW.provincenames["p23"],x:525,y:675},25:{name:uW.provincenames["p24"],x:675,y:675}}
        if (t.state == null){
            this.cont.innerHTML = '\
        <DIV class=pdxEntry><table><tr valign=bottom><TD class=xtab width=100 align=right>'+culang.mainType+': </td><TD>\
        <SELECT id="srcType">\
        <OPTION value=0>'+uW.g_js_strings.commonstr.barbariancamp+'</option>\
        <OPTION value=1>'+uW.g_js_strings.commonstr.wilderness+'</option>\
        <OPTION value=2>'+culang.mainCities+'</option>\
        <OPTION value=3>'+uW.g_js_strings.commonstr.darkForest+'</option>\
        </select></td></tr>\
        </table>\
        <DIV id="srcOpts" style="max-height:80px"></div></div>\
        <DIV id="srcResults" style="max-height:'+(Options.HauteurBoite-80)+'px; overflow:auto;"></div>';
            var psearch = document.getElementById ("pasrcType");
            m = '<TABLE><TR valign=middle><TD class=xtab width=100 align=right>&nbsp; X: </td><TD class=xtab>\
        <INPUT id="srchX" type=text size=3\> &nbsp; Y: <INPUT id="srchY" type=text size=3\>';
            m += '&nbsp;<span><select id="KsprovinceXY"><option>--'+uW.g_js_strings.commonstr.province+'--</option>';
            for (var i in Provinces) {
                m += '<option value="'+i+'">'+Provinces[i].name+'</option>';
            }
            m += '</select></span> &nbsp; <SPAN id=spInXY></span>';
            m += '</td></tr><TR><TD class=xtab align=right>'+culang.mainDistance+': </td><TD class=xtab>'+culang.shortMin+' <INPUT id=srcaDist size=4 value=0 /> '+culang.shortMax+' <INPUT id=srcDist size=4 value=10 /></td></tr>';
            m += '<TR><TD class=xtab></td><TD class=xtab><INPUT id=srcStart type=submit value="'+culang.searchStart+'"/></td></tr>';
            m += '</table>';
            document.getElementById ('srcOpts').innerHTML = m;
            var citysrc0=new CdispCityPicker ('srchdcp', document.getElementById ('spInXY'), false, t.clickCitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
            if (Options.srcTypeSelect)
                document.getElementById ('srcType').value=Options.srcTypeSelect;
            if (Options.srcaDist)
                document.getElementById ('srcaDist').value=Options.srcaDist;
            if (Options.srcDist)
                document.getElementById ('srcDist').value=Options.srcDist;
            document.getElementById ('srcType').addEventListener ('change', function() {
                Options.srcTypeSelect = document.getElementById ('srcType').value;
                saveOptions();
            }, false);
            document.getElementById ('srcaDist').addEventListener ('change', function() {
                Options.srcaDist = document.getElementById ('srcaDist').value;
                saveOptions();
            }, false);
            document.getElementById ('srcDist').addEventListener ('change', function() {
                Options.srcDist = document.getElementById ('srcDist').value;
                saveOptions();
            }, false);
            document.getElementById ('KsprovinceXY').addEventListener ('change', function() {
                if (this.value >= 1) {
                    document.getElementById ('srchX').value = Provinces[this.value].x;
                    document.getElementById ('srchY').value = Provinces[this.value].y;
                    document.getElementById ('srcDist').value = "75";
                }
            }, false);
            document.getElementById ('srcStart').addEventListener ('click', t.clickedSearch, false);
            t.state = 1;
        }
    },
    clickCitySourceSelect : function (city){
        var t = Tabs.Search;
        t.sourceCity = city;
        document.getElementById ('srchX').value=t.sourceCity.x;
        document.getElementById ('srchY').value=t.sourceCity.y;
    },
    opt : {},
    searchRunning : false,
    tilesSearched : 0,
    tilesFound : 0,
    curX : 0,
    curY : 0,
    lastX : 0,
    firstX : 0,
    firstY : 0,
    lastY : 0,
    normalizeCoord : function (x){
        if ( x >= 750)
            x -= 750;
        else if (x < 0)
            x += 750;
        return parseInt (x/5) * 5;
    },
    clickedSearch : function (){
        var t = Tabs.Search;
        if (t.searchRunning){
            t.stopSearch (''+culang.searchCanceled+'');
            return;
        }
        t.opt.searchType = document.getElementById ('srcType').value;
        t.opt.startX = parseInt(document.getElementById ('srchX').value);
        t.opt.startY = parseInt(document.getElementById ('srchY').value);
        t.opt.maxDistance = parseInt(document.getElementById ('srcDist').value);
        t.opt.maxDistanceA = parseInt(document.getElementById ('srcaDist').value);
        errMsg = '';
        if (isNaN (t.opt.startX) ||t.opt.startX<0 || t.opt.startX>749)
            errMsg = ""+culang.searchXmustBe+"<BR>";
        if (isNaN (t.opt.startY) ||t.opt.startY<0 || t.opt.startY>749)
            errMsg += ""+culang.searchYmustBe+"<BR>";
        if (isNaN (t.opt.maxDistanceA) ||t.opt.maxDistanceA<0)
            errMsg += ""+culang.searchMinGreater0+"<BR>";
        if (isNaN (t.opt.maxDistance) ||t.opt.maxDistance<1)
            errMsg += ""+culang.searchMaxGreater0+"<BR>";
        if (t.opt.maxDistance<=t.opt.maxDistanceA)
            errMsg += ""+culang.searchMaxGreaterMin+"<BR>";
        if(t.opt.maxDistanceA > 375)
            errMsg += ""+culang.searchMax375+"<BR>";
        if (errMsg != ''){
            ById('srcResults').innerHTML = '<FONT COLOR=#660000>'+culang.mainError+':</font> '+ errMsg;
            return;
        }

        t.searchRunning = true;
        document.getElementById ('srcStart').value = ''+culang.searchStop+'';
        m = '<DIV class=pdxStat><TABLE width=100% cellspacing=0><TR><TD class=xtab width=125><DIV id=statSearched></div></td>\
        <TD class=xtab align=center><SPAN id=statStatus></span></td>\
        <TD class=xtab align=right width=125><DIV id=statFound></div></td></tr></table></div>\
      <TABLE width=95%><TR valign=top><TD><DIV id=divOutTab style="max-height:'+(Options.HauteurBoite-230)+'px; overflow:auto; width:500px;"></div></td>\
      <TD id="tddivOutOpts" width=100% height=100% style="background:#e0e0f0; border:1px outset #141516; border-radius:5px;-moz-box-shadow: 2px 2px 2px 2px #141516; -webkit-box-shadow: 2px 2px 2px 2px #141516; box-shadow: 2px 2px 2px 2px #141516; height:100%; padding:5px"><DIV id=divOutOpts></div></td></tr><tr><td colspan=2><div id=KsdivKOCAttackExport style="position:absolute;background-color:white; max-height:470px; overflow-y:auto; width:600px;display:none"></div></td><input type=checkbox id=ShowHideOpts>'+culang.searchShowHideOptions+'</tr></table>';
        ById('srcResults').innerHTML = m;
        //
        ById('ShowHideOpts').addEventListener ('click', function (){
            if (ById("ShowHideOpts").checked) {
                ById("tddivOutOpts").style.display="none";
                ById("divOutTab").style.width="100%";
                ById("divOutTab").style.overflow="none";

            } else {
                ById("tddivOutOpts").style.display="block";
                ById("divOutTab").style.width="500px";
            }
        }, false);

        if (t.opt.searchType == 0)
            typeName = culang.kocBarbarianCamps;
        else if (t.opt.searchType == 1)
            typeName = culang.mainWildernes;
        else if (t.opt.searchType == 3)
            typeName = culang.mainDarkForest;
        else
            typeName = culang.mainCities;

        m = '<CENTER><B>'+culang.searchFor+' '+ typeName +'<BR>\
        '+culang.searchStartpoint+' '+ t.opt.startX +','+ t.opt.startY +'  &nbsp; '+culang.mainDistance+': '+ t.opt.maxDistanceA +' '+culang.mainTo+' '+ t.opt.maxDistance +'<BR></center>\
        <DIV class=pdxEntry><TABLE cellspacing=0 width=100%><TR align=center><TD class=xtab colspan=10><B><u>'+culang.searchOptionsHead+'</u></b><BR></td></tr>';
        if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3) {
            m += '<TR><TD class=xtab align=right>'+culang.searchLevelMin+'</td><TD class=xtab> <INPUT id=filMinLvl size=2 value='+ Options.srcMinLevel +' /></td></tr>\
        <TR><TD class=xtab align=right>'+culang.searchLevelMax+':</td><TD class=xtab> <INPUT id=filMaxLvl size=2 value='+ Options.srcMaxLevel +' /></td></tr>';
        }
        if (t.opt.searchType == 1){
            m += '<TR><TD class=xtab align=right>'+culang.mainType+':</td><TD class=xtab align=right>\
        '+culang.kocForests+'<INPUT id=woodWild type=CHECKBOX'+ (Options.woodWild?' CHECKED':'') +'></td></tr>';
            m += '<TR><TD class=xtab align=right>'+uW.g_js_strings.commonstr.grassland+'/'+uW.g_js_strings.commonstr.lake+'<INPUT  id=foodWild type=CHECKBOX '+ (Options.foodWild?' CHECKED':'') +'></td>\
        <TD class=xtab align=right>'+uW.g_js_strings.commonstr.mountain+'<INPUT id=mtnWild type=CHECKBOX '+ (Options.mtnWild?' CHECKED':'') +'></td></tr>';
            m += '<TR><TD class=xtab align=right>'+uW.g_js_strings.commonstr.plain+'<INPUT id=plnWild type=CHECKBOX '+ (Options.plnWild?' CHECKED':'') +'></td>\
        <TD class=xtab align=right>'+uW.g_js_strings.commonstr.hills+'<INPUT id=hillWild type=CHECKBOX'+ (Options.hillWild?' CHECKED':'') +'></td></tr>';
            m += '<TR><TD class=xtab align=right>'+culang.searchFilter+'</td><TD class=xtab><SELECT style="width: 135px" id=idTSSrchFilter>\
        <OPTION value=0>'+culang.mainAll+'</option>\
        <OPTION value=1>'+culang.searchFreeSel+'</option>\
        <OPTION value=2>'+culang.searchHostile+'</option>\
        <OPTION value=3>'+culang.searchNeutral+'</option>\
        <OPTION value=4>'+culang.searchNoAlliance+'</option>\
        </select></td></tr>';
        }
        if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3 ) {
            m+= '<TR><TD class=xtab align=right>'+culang.searchSort+'</td><TD class=xtab><SELECT id=filSortBy>\
              <OPTION value="level" '+ (Options.srcSortBy=='level'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.level+'</option>\
              <OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>'+culang.mainDistance+'</option>';
            if (t.opt.searchType == 1) {
                m+= '<OPTION value="play" '+ (Options.srcSortBy=='play'?'SELECTED':'')  +'>'+culang.mainPlayer+'</option>';
                m+= '<OPTION value="alli" '+ (Options.srcSortBy=='alli'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.alliance+'</option>';
            }
            m+= '</select></td></tr>\
                <TR><TD class=xtab align=right>'+culang.searchCoordsOnly+'</td><TD class=xtab><INPUT type=checkbox id=coordsOnly \></td></tr>\
                </table></div><BR><SPAN id=srchSizeWarn></span><DIV id=KspbSrcExp></div>';
        } else {

            m+= '<TR><TD class=xtab align=right >'+culang.mainShow+':</td><TD class=xtab align=left ><SELECT style="width: 135px" id=idSrchFilter>\
            <OPTION value=0>'+culang.mainAll+'</option>\
            <OPTION value=1>'+culang.searchHostile+'</option>\
            <OPTION value=2>'+culang.searchInMist+'</option>\
            <OPTION value=3>'+culang.searchAlly+'</option>\
            <OPTION value=4>'+culang.searchFriendly+'</option>\
            <OPTION value=5>'+culang.searchNeutral+'</option>\
            <OPTION value=6>'+culang.searchNoAlliance+'</option>\
            </select></td></tr>';

            m+= '<TR><TD class=xtab align=right>Trier Par :</td><TD class=xtab><SELECT id=filSortBy>\
            <OPTION value="might" '+ (Options.srcSortBy=='might'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.might+'</option>\
            <OPTION value="dist" '+ (Options.srcSortBy=='dist'?'SELECTED':'')  +'>'+culang.mainDistance+'</option>\
                  <OPTION value="play" '+ (Options.srcSortBy=='play'?'SELECTED':'')  +'>'+culang.mainPlayer+'</option>\
            <OPTION value="alli" '+ (Options.srcSortBy=='alli'?'SELECTED':'')  +'>'+uW.g_js_strings.commonstr.alliance+'</option>\
            </select></td></tr>\
            <tr><TD class=xtab align=right>'+culang.searchMightMin+'</td><TD class=xtab><input size=8 id=filPuissance value="'+Options.filPuissance+'"></td></tr>\
            <tr><TD class=xtab align=right>'+culang.searchMightMax+'</td><TD class=xtab><select id=filPuissanceMax>\
            <option value="500" '+ (Options.filPuissanceMax=='500'?'SELECTED':'')  +'>500</option>\
            <option value="2500" '+ (Options.filPuissanceMax=='2500'?'SELECTED':'')  +'>2 500</option>\
            <option value="10000" '+ (Options.filPuissanceMax=='10000'?'SELECTED':'')  +'>10 000</option>\
            <option value="50000" '+ (Options.filPuissanceMax=='50000'?'SELECTED':'')  +'>50 000</option>\
            <option value="100000" '+ (Options.filPuissanceMax=='100000'?'SELECTED':'')  +'>100 000</option>\
            <option value="500000" '+ (Options.filPuissanceMax=='100000'?'SELECTED':'')  +'>500 000</option>\
            <option value="1000000" '+ (Options.filPuissanceMax=='1000000'?'SELECTED':'')  +'>1 000 000</option>\
            <option value="100000000" '+ (Options.filPuissanceMax=='100000000'?'SELECTED':'')  +'>100 '+culang.mainMillions+'</option>\
            <option value="900000000" '+ (Options.filPuissanceMax=='900000000'?'SELECTED':'')  +'>900 '+culang.mainMillions+'</option>\</select></td></tr>\
            <TR><TD class=xtab align=right>'+culang.searchCoordsOnly+':</td><TD class=xtab><INPUT type=checkbox id=coordsOnly \></td></tr>\
            </table></div><BR><SPAN id=srchSizeWarn></span><BR><SPAN id=srchSizeWarn></span><DIV id=KspbSrcExp></div>';
        }
        ById('divOutOpts').innerHTML = m;
        if (t.opt.searchType == 1 || t.opt.searchType == 0 || t.opt.searchType == 3) {
            ById('filMinLvl').addEventListener ('change', function (){
                Options.srcMinLevel = ById('filMinLvl').value;
                saveOptions();
                t.dispMapTable ();
            }, false);
            ById('filMaxLvl').addEventListener ('change', function (){
                Options.srcMaxLevel = ById('filMaxLvl').value;
                saveOptions();
                t.dispMapTable ();
            }, false);
        }
        ById('filSortBy').addEventListener ('change', function (){
            Options.srcSortBy = ById('filSortBy').value;
            saveOptions();
            t.dispMapTable ();
        }, false);
        ById('coordsOnly').addEventListener ('change', function (){ t.dispMapTable (); }, false);
        if (t.opt.searchType == 1){
            ById('foodWild').addEventListener ('change', function(){
                Options.foodWild = ById('foodWild').checked;
                saveOptions();
                t.dispMapTable ();
            }, false);
            ById('hillWild').addEventListener ('change', function(){
                Options.hillWild = ById('hillWild').checked;
                saveOptions();
                t.dispMapTable();
            }, false);
            ById('mtnWild').addEventListener ('change', function(){
                Options.mtnWild = ById('mtnWild').checked;
                saveOptions();
                t.dispMapTable();
            }, false);
            ById('plnWild').addEventListener ('change', function(){
                Options.plnWild = ById('plnWild').checked;
                saveOptions();
                t.dispMapTable();
            }, false);
            ById('woodWild').addEventListener ('change', function(){
                Options.woodWild = ById('woodWild').checked;
                saveOptions();
                t.dispMapTable ();
            }, false);

            ById('idTSSrchFilter').addEventListener ('change', function (){
                Options.TSSrchFilter = (ById('idTSSrchFilter').value);
                saveOptions();
                t.dispMapTable ();
            }, false);
            ById('idTSSrchFilter').value = Options.TSSrchFilter;
        }
        if (t.opt.searchType == 2){

            ById('idSrchFilter').addEventListener ('change', function (){
                Options.citySrchFilter = (ById('idSrchFilter').value);
                saveOptions();
                t.dispMapTable ();
            }, false);

            ById('idSrchFilter').value = Options.citySrchFilter;


            ById('filPuissance').addEventListener ('change', function (){
                Options.filPuissance = parseInt(ById('filPuissance').value);
                saveOptions();
                t.dispMapTable ();
            }, false);
            ById('filPuissanceMax').addEventListener ('change', function (){
                Options.filPuissanceMax = parseInt(ById('filPuissanceMax').value);
                saveOptions();
                t.dispMapTable ();
            }, false);

        }

        t.mapDat = [];
        t.firstX =  t.opt.startX - t.opt.maxDistance;
        t.lastX = t.opt.startX + t.opt.maxDistance;
        t.firstY =  t.opt.startY - t.opt.maxDistance;
        t.lastY = t.opt.startY + t.opt.maxDistance;
        t.tilesSearched = 0;
        t.tilesFound = 0;
        t.curX = t.firstX;
        t.curY = t.firstY;
        var xxx = t.normalizeCoord(t.curX);
        var yyy = t.normalizeCoord(t.curY);
        document.getElementById ('statStatus').innerHTML = ''+culang.searchSearching+' '+ xxx +','+ yyy;
        setTimeout (function(){Map.request (xxx, yyy, 40, t.mapCallback)}, MAP_DELAY);
    },

    dispMapTable : function (){
        var tileNames = [uW.g_js_strings.commonstr.barbarians, uW.g_js_strings.commonstr.grassland, uW.g_js_strings.commonstr.lake, uW.g_js_strings.commonstr.woods, uW.g_js_strings.commonstr.hills, uW.g_js_strings.commonstr.mountain, uW.g_js_strings.commonstr.plain, uW.g_js_strings.commonstr.city, culang.kocBog, unsafeWindow.g_js_strings.commonstr.darkForest, 'Camelot1',' Camelot2', 'Camelot3',' Camelot4', 'Camelot5','Camelot6','Ruine'];

        var t = Tabs.Search;
        function mySort(a, b){
            if (Options.srcSortBy == 'level'){
                if ((x = a[4] - b[4]) != 0)
                    return x;
            }
            if (Options.srcSortBy == 'might'){
                if ((x = b[10] - a[10]) != 0)
                    return x;
            }
            if (Options.srcSortBy == 'alli'){

                if (a[11] < b[11]) return -1;
                else if (a[11] == b[11]) return 0;
                else return 1;

            }
            if (Options.srcSortBy == 'play'){

                if (a[9] < b[9]) return -1;
                else if (a[9] == b[9]) return 0;
                else return 1;

            }
            return a[2] - b[2];
        }

        dat = [];
        for (i=0; i<t.mapDat.length; i++){
            lvl = parseInt (t.mapDat[i][4]);
            type = t.mapDat[i][3];
            puissance = t.mapDat[i][10];
            if (t.opt.searchType == 2 && type == 7 ) {

                switch(parseInt (Options.citySrchFilter)) {
                    case 0:
                        if (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax) {
                            dat.push(t.mapDat[i]);
                        }
                        break;
                    case 1:
                        if ((t.mapDat[i][12] == ''+culang.kocHostile+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                            dat.push(t.mapDat[i]);
                        }
                        break;
                    case 2:
                        if ((t.mapDat[i][5]===true) && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                            dat.push(t.mapDat[i]);
                        }
                        break;
                    case 3:
                        if ((t.mapDat[i][12] == ''+culang.kocAllys+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                            dat.push(t.mapDat[i]);
                        }
                        break;
                    case 4:
                        if ((t.mapDat[i][12] == ''+culang.kocFriendly+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                            dat.push(t.mapDat[i]);
                        }
                        break;
                    case 5:
                        if ((t.mapDat[i][12] == ''+culang.kocNeutral+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                            dat.push(t.mapDat[i]);
                        }
                        break;
                    case 6:
                        if ((t.mapDat[i][12] == ''+culang.kocNoAlliance+'') && (Options.filPuissance<=puissance && puissance<=Options.filPuissanceMax)) {
                            dat.push(t.mapDat[i]);
                        }
                        break;
                }


            } else {
                if (lvl>=Options.srcMinLevel && lvl<=Options.srcMaxLevel){

                    if ((t.opt.searchType==3 && (type == 8 || type == 9 || type == 10 || type == 11 || type == 12 || type == 13 || type == 14 || type == 15)) || t.opt.searchType==0
                        || (Options.woodWild==1 && type == 3)
                        || (Options.hillWild==1 && type ==4)
                        || (Options.mtnWild==1 && type==5)
                        || (Options.plnWild==1 && type == 6)
                        || (Options.foodWild==1 && (type==1 || type==2)))
                        if (Options.TSSrchFilter==0)
                            dat.push (t.mapDat[i]);
                        else if (Options.TSSrchFilter==1 && t.mapDat[i][5]===false)
                            dat.push (t.mapDat[i]);
                        else if (Options.TSSrchFilter==2 && t.mapDat[i][12] ==''+culang.kocHostile+'')
                            dat.push (t.mapDat[i]);
                        else if (Options.TSSrchFilter==3 && t.mapDat[i][12] ==''+culang.kocNeutral+'')
                            dat.push (t.mapDat[i]);
                        else if (Options.TSSrchFilter==4 && t.mapDat[i][12] ==''+culang.kocNoAlliance+'')
                            dat.push (t.mapDat[i]);
                }
            }
        }

        ById('statFound').innerHTML = ''+culang.searchFound+' '+ dat.length;
        if (dat.length == 0){
            m = '<BR><center><b><i>'+culang.searchNoResult+'</i></b></center>';
        } else {
            dat.sort(mySort);
            if (ById("coordsOnly").checked)
                m = '<TABLE align=center id=srcOutTab cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>'+culang.shortCoordinate+'</td></tr>';
            else {
                if (t.opt.searchType == 0 || t.opt.searchType == 3) {
                    m = '<TABLE id=srcOutTab cellpadding=0 cellspacing=0><TR style="font-weight: bold"><TD>'+culang.shortCoordinate+'</td><TD style="padding-left: 10px">'+culang.shortDistance+'</td><TD style="padding-left: 10px;">'+culang.shortLevel+'</td><TD style="padding-left: 10px;">'+culang.mainType+'</td></tr>';
                }
                if (t.opt.searchType == 1 ) {
                    m = '<TABLE id=srcOutTab cellpadding=2 cellspacing=2><TR style="font-weight: bold"><TD>'+culang.shortCoordinate+'</td><TD style="padding-left: 10px">'+culang.shortDistance+'</td><TD style="padding-left: 10px;">'+culang.shortLevel+'</td><TD style="padding-left: 10px;">'+culang.mainType+'</td><TD style="padding-left: 10px;">'+culang.mainPlayer+'</td><td style="padding-left: 10px;">'+culang.mainMight+'</td><td style="padding-left: 10px;">'+uW.g_js_strings.commonstr.alliance+'</td><td>'+culang.mainStatus+'</td><td>'+culang.mainLastLogin+'</td></tr>';
                }
                if (t.opt.searchType == 2) {
                    m = '<TABLE id=srcOutTab cellpadding=2 cellspacing=2><TR style="font-weight: bold"><TD>'+culang.shortCoordinate+'</td><TD >'+culang.shortDistance+'</td><TD>'+culang.mainCity+'</td><TD>'+culang.mainPlayer+'</td><TD>'+culang.mainMight+'</td><td>'+uW.g_js_strings.commonstr.alliance+'</td><TD width=80% style="font-size:9px;">'+culang.mainInfo+'</td></tr>';
                }

            }
            var numRows = dat.length;
            if (numRows > 500 && t.searchRunning){
                numRows = 500;
                ById('srchSizeWarn').innerHTML = '<FONT COLOR=#600000>'+culang.mainImportant+': <i>'+culang.searchOnlyShow+' '+ dat.length +' '+culang.searchOnlyShow2+'</i></font>';
            }
            for (i=0; i<numRows; i++){
                m += '<TR valign="top"';
                if (dat[i][12]) m += 'class="'+dat[i][12]+'"';

                if (ById("coordsOnly").checked){
                    m += ' ><TD valign="top"><DIV>'+ dat[i][0] +','+ dat[i][1] +'</div></td></tr>';
                } else {
                    m += ' ><TD valign="top"><DIV>\
                 <a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ dat[i][0] +','+ dat[i][1] +')</a></div></td>';
                    if (t.opt.searchType == 2) {
                        m += '<TD align="left"  valign="top"><DIV  onclick="PTscout('+ dat[i][0] +','+ dat[i][1] +');return false;"><img src="'+IMGmarchScouting+'" title="'+culang.mainScout+' !">&nbsp;'+ dat[i][2].toFixed(2) +'</a></td><TD align=left>'+ dat[i][8] +'</td><TD valign="top">'+dat[i][9]+'</td><TD valign="top">'+addCommasInt(dat[i][10])+'</td><td>'+dat[i][11]+'</td><td>';
                        if (dat[i][5]) {
                            m += '<DIV onclick="BoPTscout('+ dat[i][0] +','+ dat[i][1] +');return false;"><A style="font-size:9px;" >Eclairer</a></div>';
                        } else {
                            m += '<DIV onclick="BoPTpd(this, '+ dat[i][7] +')"><A style="font-size:9px;" >'+culang.searchDetails+'</a></div> <DIV style="" onclick="BoPTpd2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainCastle+'</a></div>\
                     <DIV style="" onclick="BoPCpo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainStatus+'</a></div>\
                    <DIV style="" onclick="BoPCplo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainLastLogin+'</a></div>';
                            m+= '</td></tr>';
                        }
                    } else {
                        m += '<TD align=right  valign="top">'+ dat[i][2].toFixed(2) +' &nbsp; </td><TD align=right>'+ dat[i][4] +'</td><TD> &nbsp; '+ tileNames[dat[i][3]];
                        +'</td>';
                        if (t.opt.searchType == 1) {
                            if (dat[i][5]) {
                                m += '<td>'+dat[i][9]+'<td>'+addCommasInt(dat[i][10])+'</td><td>'+dat[i][11]+'</td>';

                                if (dat[i][7] && dat[i][7]!=0) {
                                    m+='<td><DIV style="" onclick="BoPCpo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainStatus+'</a></div></td><td><DIV style="" onclick="BoPCplo2(this, '+ dat[i][7] +')"><A style="font-size:9px;">'+culang.mainLastLogin+'</a></div></td>';
                                } else {
                                    m+='<td>&nbsp;</td><td>&nbsp;</td>';
                                }


                            } else  {
                                m +='<td colspan=5 style="text-align=center"><i><span class="boldGreen">'+culang.searchFree+'</span></i>';
                            }
                        }else{
                            m+="<td></td>";
                        }
                        m +='</tr>';
                    }
                }
            }
            m += '</table>';
        }
        ById('divOutTab').innerHTML = m;
        dat = null;
    },

    mapDat : [],

    stopSearch : function (msg){
        var t = Tabs.Search;
        document.getElementById ('statStatus').innerHTML = '<FONT color=#ffaaaa>'+ msg +'</font>';
        document.getElementById ('srcStart').value = ''+culang.searchStart+'';
        ById('srchSizeWarn').innerHTML = '';
        if (t.opt.searchType==0){
            ById('KspbSrcExp').innerHTML = '<CENTER>'+ strButton20(''+culang.searchExport+'', 'id=KspbSrcDoExp') +'</center>';
            document.getElementById ('KspbSrcDoExp').addEventListener ('click', t.exportKOCattack, false);
        }
        if (t.opt.searchType==3){
            document.getElementById ('KspbSrcExp').innerHTML = '<CENTER>'+ strButton20(''+culang.mainAttack+'', 'id=KsSrcDoFS') +'</center>';
            document.getElementById ('KsSrcDoFS').addEventListener ('click', t.generateFSList, false);
        }
        if (t.opt.searchType==2){
            document.getElementById ('KspbSrcExp').innerHTML = '<CENTER>'+ strButton20(''+culang.searchScoutList+'', 'id=pbSrcDoScout') +'</center>';
            document.getElementById ('pbSrcDoScout').addEventListener ('click', t.generateScoutList, false);
        }
        t.searchRunning = false;
    },
    generateFSList :function () {
        var t = Tabs.Search;
        var bulkFS = [];
        for (i=0; i<t.mapDat.length; i++){
            bulkFS.push({x:t.mapDat[i][0], y:t.mapDat[i][1], dist:t.mapDat[i][2], lvl:parseInt(t.mapDat[i][4])});
        }
        bulkFS = bulkFS.sort(function sort(a,b) {a = parseInt(a['dist']);b = parseInt(b['dist']);return a == b ? 0 : (a < b ? -1 : 1);});
        if(t.selectedCity == null)
            t.selectedCity = Cities.cities[0];
        t.ShowFSList (bulkFS, t.selectedCity);

    },
    ShowFSList:function (coordlist, city) {
        var t = Tabs.Search;
        t.FScity = city;
        if(t.popFS==null){
            t.popFS = new CPopup ('KssrcFS', 0,0, 380,600, true, function (){t.popFS.destroy(); t.popFS=null;});
            t.popFS.centerMe (mainPop.getMainDiv());
            t.popFS.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.searchDarkForestOptions+'</div>';
        }
        var m = '<div>'+uW.g_js_strings.commonstr.level+': <select id=KssrcFSLevel><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select>&nbsp<input type=button id=KssrcFSSave value="'+culang.buttonSave+'"><br>';
        for (r=1; r<16; r++){
            m += '<DIV style="float:left;"><img height=20 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg>&nbsp;<input style="border:1px solid black;height:16px;font-size:11px;" id="KsFsUnits'+r+'" type=text size=7 value="0"></DIV>';
        }
        m += '</div><br><br><br><br><br><br><DIV>'+culang.mainCastle+': <span id=KssrcFScitypick> </span></div><BR>';
        m += '<DIV class=pdxStat>'+culang.searchSentScouts+' <span id=KssrcFScity>'+city.name+'</span> '+culang.searchSentScouts2+' <BR> '+culang.mainTargets+': '+coordlist.length+'</div>';
        m += '<DIV style="max-height:220px; overflow-y:auto;"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class=pbTabPadNW><TR style="font-weight:bold; background-color:white"><TD width=15><input type=checkbox id=pbsrcScout_All /></td><TD>'+culang.shortCoordinate+'</td><td><select id=pbsrcScout_lvl><option value="">'+uW.g_js_strings.commonstr.level+'</option><option value=1>1</option><option value=2>2</option><option value=3>3</option><option value=4>4</option><option value=5>5</option><option value=6>6</option><option value=7>7</option><option value=8>8</option><option value=9>9</option><option value=10>10</option></select></td><td>'+culang.shortDistance+'</td></tr>';
        for(i=0; i<coordlist.length; i++){
            m += '<TR style="background-color:white"><TD><input type=checkbox name="pbsrcFSCheck" id="pbsrcScoutCheck_'+coordlist[i].x+'_'+coordlist[i].y+'_'+coordlist[i].lvl+'" value="'+coordlist[i].x+'_'+coordlist[i].y+'_'+coordlist[i].lvl+'" /></td><TD>'+coordlist[i].x+ ','+coordlist[i].y+'</td><td>'+coordlist[i].lvl+'</td><td>'+coordlist[i].dist+'</td></tr>';
        }
        m += '</table></div>';
        m += '<BR><CENTER>'+ strButton20(''+culang.searchStartScout+'', 'id=pbSrcStartScout') +'</center>';
        m += '<CENTER><DIV style="width:100%; max-height:100px; overflow-y:auto;" id=pbSrcScoutResult></DIV></center>';


        t.popFS.getMainDiv().innerHTML = m;
        new CdispCityPicker ('KsFSPick', ById('KssrcFScitypick'), false, function(c,x,y){ById('KssrcFScity').innerHTML = c.name; t.attackcity = c; }, city.idx);

        t.popFS.show(true);

        ById('KssrcFSSave').addEventListener('click', t.enregistrerscrLevel, false);
        ById('KssrcFSLevel').addEventListener('click', t.changescrLevel, false);
        ById('pbsrcScout_All').addEventListener('change', function(){
            for(k in document.getElementsByName('pbsrcFSCheck'))
                document.getElementsByName('pbsrcFSCheck')[k].checked = ById('pbsrcScout_All').checked;
        }, false);
        ById('pbsrcScout_lvl').addEventListener('change', function(){
            if (ById('pbsrcScout_lvl').value!="") {
                for(k in document.getElementsByName('pbsrcFSCheck')) {
                    var lvl = document.getElementsByName('pbsrcFSCheck')[k].value;
                    if (lvl!==undefined) {
                        var lvll = lvl.split("_");
                        if (lvll[2]==ById('pbsrcScout_lvl').value){
                            document.getElementsByName('pbsrcFSCheck')[k].checked = true;
                        }
                    }
                }
            }
        }, false);



        ById('pbSrcStartScout').addEventListener('click', t.clickedStartFSAttack, false);

        t.changescrLevel();
    },
    changescrLevel: function() {
        var t = Tabs.Search;
        if (Options.AttackFSUnits[ById('KssrcFSLevel').value]!==undefined) {
            for (r=1; r<16; r++){
                ById('KsFsUnits'+r).value=Options.AttackFSUnits[ById('KssrcFSLevel').value][r];
            }
        }
    },
    enregistrerscrLevel: function() {
        var t = Tabs.Search;
        Options.AttackFSUnits[ById('KssrcFSLevel').value]=[];
        for (r=1; r<16; r++){
            Options.AttackFSUnits[ById('KssrcFSLevel').value][r] = ById('KsFsUnits'+r).value;
        }
        saveOptions ();
        t.changescrLevel();
    },
    attacking : false,
    attackcity : null,
    doFSAttack: function(list, city){
        var t = Tabs.Search;
        ById('pbSrcScoutResult').innerHTML = '';
        if(list.length < 1){
            ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+culang.searchNoCoords+'</span><br>';
            t.clickedStartFSAttack();
            return;
        }
        for (var lvl=1;lvl<11; lvl++){
            var totalunit=0;
            for (r=1; r<16; r++){
                if (Options.AttackFSUnits[lvl]!=undefined) {
                    totalunit += parseInt(Options.AttackFSUnits[lvl][r]);
                    if(parseInt(Seed.units['city'+city.id]['unt'+r]) < Options.AttackFSUnits[lvl][r]){
                        ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+culang.mainError+': '+unsafeWindow.unitcost['unt'+r][0]+' '+culang.searchScoutNoAvailable+' '+lvl+'</span><br>';
                        t.clickedStartFSAttack();
                        return;
                    }
                }
            }
        }
        t.doFSAttackCount(list, city, list.length, 0);

    },
    doFSAttackCount : function(list, city, total, count){
        var t = Tabs.Search;

        if(!t.attacking){
            ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+culang.searchStopScout+'</span><BR>';
            ById('pbSrcStartScout').className = 'button20 ptButton20';
            ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchStartScout+'</span>';
            return;
        }
        if(total <= (count)){
            ById('pbSrcScoutResult').innerHTML += ''+culang.mainHDone+'<BR>';
            t.clickedStartFSAttack();
            return;
        }
        var rinfo = getRallypointInfo(city.id);
        var rallypointlevel = rinfo.maxMarches;
        var slots = rinfo.usedSlots;
        if(slots >= rallypointlevel){
            setTimeout(function(){t.doFSAttackCount(list, city, total, count)}, 10000);
            ById('pbSrcScoutResult').innerHTML += ''+culang.searchSentScoutsWaitForRP+'<br>';
            return;
        }
        var coords = list[count].split("_");
        if(coords[0] == 'undefined' || coords[1] == 'undefined'){
            ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+culang.mainError+': '+culang.searchCoordsInvalid+'</span>';
            t.clickedStartFSAttack();
            return;
        }
        ById('pbSrcScoutResult').innerHTML += ''+culang.searchSentScoutsAttacks+' '+coords[0]+','+coords[1]+' '+culang.searchSentScoutsAttacks2+'';
        ById('pbsrcScoutCheck_'+coords[0]+'_'+coords[1]+'_'+coords[2]).checked = false;
        t.sendAttackFS(coords[0], coords[1], coords[2], city, count, function(c){t.doFSAttackCount(list, city, total, c)});
    },
    sendAttackFS : function(x, y, lvl, city, count, notify){
        var t = Tabs.Search;
        count = parseInt(count);
        var totalunit = 0;
        for (r=1; r<16; r++) {
            if (Options.AttackFSUnits[lvl]!=undefined)
                totalunit += parseInt(Options.AttackFSUnits[lvl][r]);
        }
        if (totalunit>0) {


            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.cid = city.id;
            params.kid = 0;
            params.type = 4;
            params.xcoord = x;
            params.ycoord = y;
            for (r=1; r<16; r++)
                params['u'+r]=parseInt(Options.AttackFSUnits[lvl][r]);
            var knt = new Array();
            for (k in Seed.knights['city' + city.id]){
                if (Seed.knights['city' + city.id][k]["knightStatus"] == 1 && Seed.leaders['city' + city.id]["resourcefulnessKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["politicsKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["combatKnightId"] != Seed.knights['city' + city.id][k]["knightId"] && Seed.leaders['city' + city.id]["intelligenceKnightId"] != Seed.knights['city' + city.id][k]["knightId"]){
                    knt.push ({
                        Name:   Seed.knights['city' + city.id][k]["knightName"],
                        Combat:    Seed.knights['city' + city.id][k]["combat"],
                        ID:    Seed.knights['city' + city.id][k]["knightId"],
                    });
                }
            }
            knt = knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
            if (knt[0]) {
                params.kid= knt[0]["ID"];
                new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                    method: "post",
                    parameters: params,
                    loading: true,
                    onSuccess: function (rslt) {
                        rslt = eval("(" + rslt.responseText + ")");
                        if (rslt.ok) {
                            var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                            var ut = unixTime();
                            var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                            var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                            for(i = 0; i <= unitsarr.length; i++){
                                if(params["u"+i]){
                                    unitsarr[i] = params["u"+i];
                                }
                            }
                            var currentcityid = params.cid;
                            unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                            if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                            ById('pbSrcScoutResult').innerHTML += ''+culang.searchScoutSent+'<BR>';
                            if (notify)
                                setTimeout(function(){ notify(count+1); }, 1500);
                        } else {
                            if (rslt.user_action) {
                                ById('pbSrcScoutResult').innerHTML += '<span title="'+rslt.msg+'">'+culang.searchScoutCaptcha+'</span><BR>';

                            } else {
                                if (rslt.error_code==104 && rslt.msg==""+culang.getScoutError+"") {
                                    ById('pbSrcScoutResult').innerHTML += '<span title="'+rslt.msg+'">'+culang.searchScoutBog+'</span><BR>';
                                    if (notify)
                                        setTimeout(function(){ notify(count+1); }, 10000);
                                } else {
                                    ById('pbSrcScoutResult').innerHTML += '<span title="'+rslt.msg+'">'+culang.mainError+'...</span><BR>';
                                    if (notify)
                                        setTimeout(function(){ notify(count); }, 10000);
                                }
                            }
                        }
                    },
                    onFailure: function () {}
                });

            } else {
                ById('pbSrcScoutResult').innerHTML += ''+culang.searchScoutKnightError+'<BR>';
                if (notify)
                    setTimeout(function(){ notify(count); }, 1000);
            }

        } else {

            ById('pbSrcScoutResult').innerHTML += '<span>'+culang.searchScoutNoParameterError+'</span><BR>';
            setTimeout(function(){ notify(count+1); }, 500);

        }


    },
    generateScoutList : function (){
        var t = Tabs.Search;
        var bulkScout = [];
        for (i=0; i<t.mapDat.length; i++){

            if (t.mapDat[i][3] == 7){

                if(t.mapDat[i][10] >= Options.filPuissance || t.mapDat[i][5]){
                    if((Options.citySrchFilter=='1' && t.mapDat[i][12] == ''+culang.kocHostile+'') ||
                        (Options.citySrchFilter=='2' && t.mapDat[i][5]===true) ||
                        (Options.citySrchFilter=='3' && t.mapDat[i][12] == ''+culang.kocAllys+'') ||
                        (Options.citySrchFilter=='4' && t.mapDat[i][12]  == ''+culang.kocFriendly+'') ||
                        (Options.citySrchFilter=='5' && t.mapDat[i][12] == ''+culang.kocNeutral+'') ||
                        (Options.citySrchFilter=='6' && t.mapDat[i][12] == ''+culang.kocNoAlliance+'') ||
                        (Options.citySrchFilter=='0'))
                        bulkScout.push({x:t.mapDat[i][0], y:t.mapDat[i][1], dist:t.mapDat[i][2]});
                }
            }
        }
        if(t.selectedCity == null)
            t.selectedCity = Cities.cities[0];
        t.ShowScoutList (bulkScout, t.selectedCity);
    },
    ShowScoutList : function (coordlist, city){
        var t = Tabs.Search;
        var popScout = null;
        t.scoutcity = city;

        if(popScout==null){
            popScout = new CPopup ('pbsrcscout', 0,0, 350,500, true, function (){popScout.destroy(); popScout=null;});
            popScout.centerMe (mainPop.getMainDiv());
        }
        var m = '<DIV>'+culang.searchScoutAmount+' <input id=pbsrcScoutAmt value="'+Options.srcScoutAmt+'" /></div><BR>';
        m += '<DIV>'+culang.mainCastle+': <span id=pbsrcScoutcitypick> </span></div><BR>';
        m += '<DIV class=pdxStat>'+culang.searchSentScouts+' <span id=pbsrcScoutcity>'+city.name+'</span> '+culang.searchSentScouts2+' <BR> '+culang.mainTargets+': '+coordlist.length+'</div>';
        m += '<DIV style="max-height:220px; overflow-y:auto;"><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabPadNW><TR style="font-weight:bold; background-color:white"><TD width=15><input type=checkbox id=pbsrcScout_All /></td><TD>'+culang.searchScoutTargetCoords+'</td></tr>';
        for(i=0; i<coordlist.length; i++){
            m += '<TR style="background-color:white"><TD><input type=checkbox name=pbsrcScoutCheck id="pbsrcScoutCheck_'+coordlist[i].x+'_'+coordlist[i].y+'" value="'+coordlist[i].x+'_'+coordlist[i].y+'" /></td><TD>'+coordlist[i].x+','+coordlist[i].y+'</td></tr>';
        }
        m += '</table></div>';
        m += '<BR><CENTER>'+ strButton20(''+culang.searchScoutsStart+'', 'id=pbSrcStartScout') +'</center>';
        m += '<CENTER><DIV style="width:70%; max-height:75px; overflow-y:auto;" id=pbSrcScoutResult></DIV></center>';
        popScout.getMainDiv().innerHTML = m;
        new CdispCityPicker ('pbScoutPick', ById('pbsrcScoutcitypick'), false, function(c,x,y){ById('pbsrcScoutcity').innerHTML = c.name; t.scoutcity = c; }, city.idx);
        popScout.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.searchScoutsHead+'</div>';
        popScout.show(true);

        ById('pbsrcScoutAmt').addEventListener('change', function(){
            Options.srcScoutAmt = parseInt(ById('pbsrcScoutAmt').value);
            saveOptions();
        }, false);
        ById('pbsrcScout_All').addEventListener('change', function(){
            for(k in document.getElementsByName('pbsrcScoutCheck'))
                document.getElementsByName('pbsrcScoutCheck')[k].checked = ById('pbsrcScout_All').checked;
        }, false);
        ById('pbSrcStartScout').addEventListener('click', t.clickedStartScout, false);
    },
    scouting : false,
    scoutcity : null,
    doScout : function(list, city){
        var t = Tabs.Search;
        ById('pbSrcScoutResult').innerHTML = '';
        if(list.length < 1){
            ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+culang.mainError+': '+culang.searchNoCoords+'</span>';
            t.clickedStartScout();
            return;
        }
        if(parseInt(Seed.units['city'+city.id]['unt'+3]) < Options.srcScoutAmt){
            ById('pbSrcScoutResult').innerHTML = '<SPAN class=boldRed>'+culang.mainError+': '+culang.searchNoScouts+'</span>';
            t.clickedStartScout();
            return;
        }
        t.doScoutCount(list, city, list.length, 0);

    },
    clickedStartScout : function(){
        var t = Tabs.Search;
        if(t.scouting == false){
            t.scouting = true;
            var ScoutList = [];
            for(k=0; k<document.getElementsByName('pbsrcScoutCheck').length; k++){
                if(document.getElementsByName('pbsrcScoutCheck')[k].checked){
                    ScoutList.push(document.getElementsByName('pbsrcScoutCheck')[k].value);
                }
            }
            t.doScout(ScoutList, t.scoutcity);
            ById('pbSrcStartScout').className = 'button20 pbButCancel';
            ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchStop+'</span>';
        } else {
            t.scouting = false;
            ById('pbSrcStartScout').className = 'button20 ptButton20';
            ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchScoutsStart+'</span>';
        }
    },
    doScoutCount : function(list, city, total, count){
        var t = Tabs.Search;
        if(!t.scouting){
            ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+culang.searchStop+'</span><BR>';
            ById('pbSrcStartScout').className = 'button20 ptButton20';
            ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchScoutsStart+'</span>';
            return;
        }
        if(total <= (count)){
            ById('pbSrcScoutResult').innerHTML += ''+culang.mainHDone+'<BR>';
            t.clickedStartScout();
            return;
        }
        var rinfo = getRallypointInfo(city.id);
        var rallypointlevel = rinfo.maxMarches;
        var slots = rinfo.usedSlots;
        if(slots >= rallypointlevel){
            setTimeout(function(){t.doScoutCount(list, city, total, count)}, 10000);
            ById('pbSrcScoutResult').innerHTML += ''+culang.searchSentScoutsWaitForRP+'<br>';
            return;
        }
        var coords = list[count].split("_");
        if(coords[0] == 'undefined' || coords[1] == 'undefined'){
            ById('pbSrcScoutResult').innerHTML += '<SPAN class=boldRed>'+culang.mainError+': '+culang.searchCoordsInvalid+'</span>';
            t.clickedStartScout();
            return;
        }
        ById('pbSrcScoutResult').innerHTML += ''+culang.searchSentScouts+' '+coords[0]+','+coords[1]+' '+culang.searchSentScouts2+'';
        ById('pbsrcScoutCheck_'+coords[0]+'_'+coords[1]).checked = false;
        t.sendScout(coords[0], coords[1], city, count, function(c){t.doScoutCount(list, city, total, c)});
    },
    sendScout : function(x, y, city, count, notify){
        var t = Tabs.Search;
        count = parseInt(count);
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = city.id;
        params.kid = 0;
        params.type = 3;
        params.xcoord = x;
        params.ycoord = y;
        params.u3 = Options.srcScoutAmt;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (rslt) {
                rslt = eval("(" + rslt.responseText + ")");
                if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unixTime();
                    var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                    var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                    for(i = 0; i <= unitsarr.length; i++){
                        if(params["u"+i]){
                            unitsarr[i] = params["u"+i];
                        }
                    }
                    var currentcityid = params.cid;
                    unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                    ById('pbSrcScoutResult').innerHTML += ''+culang.searchScoutSent+'<BR>';
                    if (notify)
                        setTimeout(function(){ notify(count+1); }, 1000);
                } else {
                    ById('pbSrcScoutResult').innerHTML += ''+culang.searchFailedAttempt+'<BR>';
                    if (notify)
                        setTimeout(function(){ notify(count); }, 1000);
                }
            },
            onFailure: function () {}
        });
    },
    getRallypoint: function(cityId){
        var t = Tabs.Search;
        cityId = 'city'+cityId;
        for (o in Seed.buildings[cityId]){
            var buildingType = parseInt(Seed.buildings[cityId][o][0]);
            var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
            if (buildingType == 12){
                return parseInt(buildingLevel);
                break;
            }
        }
        return 0;
    },
    clickedStartFSAttack : function(){
        var t = Tabs.Search;
        if(t.attacking == false){
            t.attacking = true;
            var ScoutList = [];
            for(k=0; k<document.getElementsByName('pbsrcFSCheck').length; k++){
                if(document.getElementsByName('pbsrcFSCheck')[k].checked){
                    ScoutList.push(document.getElementsByName('pbsrcFSCheck')[k].value);
                }
            }
            t.doFSAttack(ScoutList, t.attackcity);
            ById('pbSrcStartScout').className = 'button20 pbButCancel';
            ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchStopScout+'</span>';
        } else {
            t.attacking = false;
            ById('pbSrcStartScout').className = 'button20 ptButton20';
            ById('pbSrcStartScout').innerHTML = '<SPAN>'+culang.searchStartScout+'</span>';
        }
    },
    clickedPlayerCheckOnline : function (span, uid){
        var t = Tabs.AllianceList;
        var s = Tabs.Search;
        span.onclick = '';
        span.innerHTML = ""+culang.searchPlayerCheckOnline+"";
        t.fetchPlayerStatusSimple (uid, function (r) {s.gotPlayerStatus(r, span, uid)});
    },

    clickedPlayerGetLastLogin : function (span, uid){
        var t = Tabs.AllianceList;
        var s = Tabs.Search;
        span.onclick = '';
        span.innerHTML = ""+culang.searchLastLogin+"";
        t.fetchPlayerLastLogin (uid, function (r) {s.gotPlayerLastLogin(r, span)});
    },
    gotPlayerStatus : function (rslt, span,uid){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            span.innerHTML = rslt.errorMsg;
            return;
        }

        var p = rslt.data;
        if (p[uid] == true) {
            m = '<span style="color:green"><b>'+culang.movementPlayerCheckOn+'</b></span>';
        } else {
            m = '<span style="color:red"><b>'+culang.movementPlayerCheckOff+'</b></span>';
        }
        span.innerHTML = m + '';
    },

    gotPlayerLastLogin : function (rslt, span){
        var t = Tabs.AllianceList;
        if (!rslt.ok){
            span.innerHTML = rslt.errorMsg;
            return;
        }

        var p = rslt.playerInfo;
        var lastLogin = rslt.playerInfo.lastLogin;

        if (lastLogin) {
            m = '<span style="color:black">'+lastLogin+'</span>';
        } else {
            m = '<span style="color:red">?</span>';
        }
        span.innerHTML = m + '';
    },
    exportKOCattack : function (){
        var t = Tabs.Search;
        var bulkAdds = {};
        for (i=1; i<11; i++)
            bulkAdds['lvl'+ i] = [];
        for (i=0; i<t.mapDat.length; i++){
            var lvl = parseInt (t.mapDat[i][4]);
            if (lvl>=Options.srcMinLevel && lvl<=Options.srcMaxLevel && t.mapDat[i][3]==0)
                bulkAdds['lvl'+ lvl].push({x:t.mapDat[i][0], y:t.mapDat[i][1]});
        }
        exportToKOCattackKs.doExport (bulkAdds, t.selectedCity);
    },
    mapCallback : function (left, top, width, rslt){
        function insertRow (x, y, msg){
            row = ById('srcOutTab').insertRow(-1);
            row.insertCell(0).innerHTML = x +','+ y;
            row.insertCell(1).innerHTML = distance (t.opt.startX, t.opt.startY, x, y);
            row.insertCell(2).innerHTML = msg;
        }
        var t = Tabs.Search;
        if (!t.searchRunning)
            return;
        if (!rslt.ok){
            t.stopSearch (''+culang.mainError+': '+ rslt.errorMsg);
            return;
        }
        if (rslt.error_code == 9) {
            document.getElementById ('statStatus').innerHTML = 'MAP-Error (60sec): '+ left +','+ top;
            setTimeout (function(){
                document.getElementById ('statStatus').innerHTML = ''+culang.searchSearching+' '+ left +','+ top;
                Map.request (left, top, 40, t.mapCallback);
            }, 61000);
            return;
        }
        map = rslt.data;
        var userInfo = rslt.userInfo;
        var alliance = rslt.allianceNames;
        for (k in map){
            if (t.opt.searchType==0 && map[k].tileType==51 && !map[k].tileCityId ) {
                type = 0;
            } else if (t.opt.searchType==1 && map[k].tileType>=10 &&  map[k].tileType<=50) {
                if (map[k].tileType == 10)
                    type = 1;
                else if (map[k].tileType == 11)
                    type = 2;
                else
                    type = (map[k].tileType/10) + 1;
            } else if (t.opt.searchType==2 && map[k].tileCityId >= 0 && map[k].tileType > 50 && map[k].cityName) {
                type = 7;
            } else if (t.opt.searchType==3 && map[k].tileType==54) {
                type=9;
            } else if (t.opt.searchType==3 && map[k].tileType>100) {
                type=9 + (map[k].tileType-100);

            } else {
                continue;
            }
            dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
            if (dist <= t.opt.maxDistance && dist >= t.opt.maxDistanceA){
                if (t.opt.searchType==2) {
                    var isMisted = map[k].tileUserId == 0 || false;
                    var uu = 'u'+map[k].tileUserId;
                    var aU = ''+culang.mainUnknown+'';
                    var aD = ''+culang.mainUnknown+'';
                    var mightU = 0;
                    var nameU = ''+culang.mainUnknown+'';
                    if (isMisted) {
                        nameU = ''+culang.mainInFog+'';
                        mightU = 0;
                    } else {
                        if (userInfo[uu] ) {
                            nameU = "<a onclick=getInfoForAnUser('"+ map[k].tileUserId +"');>"+ userInfo[uu].n +"</a>";
                            mightU = userInfo[uu].m;
                            aD = getDiplomacy(userInfo[uu].a);
                            if ( alliance && alliance['a'+userInfo[uu].a] ) {
                                aU = alliance['a'+userInfo[uu].a];
                            }
                            else {
                                aU = '----';
                                aD = ''+culang.kocNoAlliance+'';
                            }
                        }
                    }
                    t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isMisted, map[k].tileCityId, map[k].tileUserId, map[k].cityName,nameU,mightU,aU,aD ]);
                } else {
                    isOwned = map[k].tileUserId>0 || map[k].misted;
                    var uu = 'u'+map[k].tileUserId;
                    var aU = ''+culang.mainUnknown+'';
                    var aD = ''+culang.mainUnknown+'';
                    var nameU = ''+culang.mainUnknown+'';
                    var mightU = 0;
                    if (map[k].misted) {
                        nameU = ''+culang.mainInFog+'';
                    }else {
                        if (userInfo[uu] ) {
                            var nameU = "<a onclick=getInfoForAnUser('"+ map[k].tileUserId +"');>"+ userInfo[uu].n +"</a>";
                            mightU = userInfo[uu].m;
                            aD = getDiplomacy(userInfo[uu].a);
                            if ( alliance && alliance['a'+userInfo[uu].a] ) {
                                aU = alliance['a'+userInfo[uu].a];
                            }
                        }else {
                            var nameU = ''+culang.mainUnknown+'';
                        }
                    }
                    t.mapDat.push ([map[k].xCoord, map[k].yCoord, dist, type, map[k].tileLevel, isOwned, map[k].tileCityId, map[k].tileUserId, map[k].cityName, nameU, mightU, aU, aD]);
                }
                ++t.tilesFound;
            }
        }
        t.tilesSearched += (40*40);
        ById('statSearched').innerHTML = ''+culang.searchSearched+' '+ t.tilesSearched;
        t.dispMapTable();
        t.curX += 40;
        if (t.curX > t.lastX){
            t.curX = t.firstX;
            t.curY += 40;
            if (t.curY > t.lastY){
                t.stopSearch (''+culang.mainHDone+'');
                return;
            }
        }
        var x = t.normalizeCoord(t.curX);
        var y = t.normalizeCoord(t.curY);
        document.getElementById ('statStatus').innerHTML = ''+culang.searchSearching+' '+ x +','+ y;
        setTimeout (function(){Map.request (x, y, 40, t.mapCallback)}, MAP_DELAY);
    },
};

function saveCrestData (){
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('CrestData_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(CrestData));}, 0);
}
function readCrestData (){
    var serverID = getServerId();
    s = GM_getValue ('CrestData_' + Seed.player['name'] + '_' +serverID);
    if (s != null) {
        opts = JSON2.parse (s);
        for (var i = 0; i < opts.length; i++) {
            CrestData[i] = new CrestFunc(opts[i]);
        }
    }
}

var RepairAuto = {
    timer : null,
    repairtimer: null,
    init: function (){
        if (!Options.salvageconfig.Repairrunning) return;
        if (upgradeData.active == true) {
            upgradeData.active = false;
            saveUpgradeData();
            //return;
        }
        RepairAuto.setEnable();
    },
    setEnable: function (){
        var t = RepairAuto;
        clearTimeout (t.repairtimer);
        t.tableau=[];
        t.repairtimer = setTimeout (t.count, 1*1000);
    },

    count:function() {
        var t = RepairAuto;
        var lignauto = Seed.throne.rowNum * 5, i=uW.kocThroneItems;
        var nbl=0;
        t.tableau=[];
        clearTimeout (t.repairtimer);
        if (!Options.salvageconfig.Repairrunning) return;

        for (var z in i) {
            if (i[z].id) {
                e=uW.kocThroneItems[i[z].id];
                if (e) {
                    nbl++;
                    if (e.isBroken && nbl<=lignauto ) {
                        if (Seed.queue_throne) {
                            if (Seed.queue_throne.itemId!=e.id)
                                t.tableau.push(i[z].id);
                        } else {
                            t.tableau.push(i[z].id);
                        }
                    }
                }
            }
        }
        var timeLeft=-1;
        if (Seed.queue_throne) {
            if (Seed.queue_throne.end)
                timeLeft = Seed.queue_throne.end - uW.unixtime();
        }
        if (t.tableau.length>0 && timeLeft<0) {
            var itemId = t.tableau[Math.floor(Math.random()*t.tableau.length)];
            actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairOK+" " + uW.kocThroneItems[itemId].name + " "+culang.throneStuffRepairOK2+" " + t.tableau.length + "");
            t.repair(itemId);
        } else {
            if (timeLeft>0) {
                actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairAlready+" "+timeLeft+""+culang.throneStuffRepairAlready2+"");
                t.repairtimer = setTimeout (t.count, (timeLeft+5)*1000);
            } else {
                actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffNoItemToDelete5Min+"");
                t.repairtimer = setTimeout (t.count, (5*60)*1000);
            }
        }
    },

    repairId:0,
    repariend:null,
    countRepair:0,
    clearRepair:function() {
        var t = RepairAuto;
        if (t.repairId != 0) {
            unsafeWindow.kocThroneItems[t.repairId].isBroken = false;
            unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
            t.repairId = 0;
        }
    },
    repair: function(id) {
        var t = RepairAuto;
        clearTimeout (t.repairtimer);
        if (!Options.salvageconfig.Repairrunning) return;
        if (uW.kocThroneItems[id]) {
            var params = uW.Object.clone(uW.g_ajaxparams);
            params.action="timeRepair";
            params.ctrl="throneRoom\\ThroneRoomServiceAjax";
            params.throneRoomItemId=id;
            uW.ajax.Request(uW.g_ajaxpath+"ajax/_dispatch53.php"+uW.g_ajaxsuffix,{method:"post",parameters:params,loading:true,
                onSuccess:function(transport) {
                    var m = eval("(" + transport.responseText + ")");
                    if (m.ok === true){
                        Seed.queue_throne.start = uW.unixtime();
                        Seed.queue_throne.end = m.eta; //uW.unixtime() + L;
                        Seed.queue_throne.itemId = id;
                        t.repairId = id;
                        t.repairend = m.eta;
                        unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);
                        var x = m.eta - unixTime();
                        setTimeout(t.clearRepair, (x+1)*1000);
                        t.countRepair=0;
                        duree= Seed.queue_throne.end - Seed.queue_throne.start + 5;
                        actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairOK+" " + uW.kocThroneItems[id].name + " "+culang.throneStuffRepairOK2+" " +duree +""+culang.shortSeconds+"");
                        t.repairtimer = setTimeout (t.count, (duree)*1000);
                    } else {
                        t.countRepair++;
                        actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairError+" " + uW.kocThroneItems[id].name);
                        if (t.countRepair>5) {
                            t.countRepair=0;
                            t.repairtimer = setTimeout (t.count, (2*60)*1000);
                        } else {
                            setTimeout(function() { t.repair(id); },2000);
                        }

                    }
                }
            });

        } else {
            actionLog(""+culang.tabLabelThrone+"", ""+culang.throneStuffRepairNoID+"");
            t.repairtimer = setTimeout (t.count, (2*60)*1000);
        }
    },
}
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/ThroneStuff.js">
/************************************************************************************
 *                        KOC POWER - TABS THRONE STUFF                                *
 ************************************************************************************/
Tabs.ThroneStuff = {
    tabOrder : TabOptions.toThroneStuff,
    tabLabel : culang.tabLabelThroneStuff,
    cont : null,
    curTabBut : null,
    curTabName : null,
    SelId:null,
    log:[],
    SalvageLog:[],
    SalvagePreviewList:[],
    timersalvage:null,
    setRepairTimer:null,
    setActionTimer:null,
    SalvageArray:[],
    SalvageArrayP1:[],
    SalvageRunning:false,
    LastDeleted:0,
    viewstats:null,
    EquipType: ["Advisor","Banner","Chair","Table","Windows","Trophy", "Candelabrum"],

    init : function (div){
        var t = Tabs.ThroneStuff;
        t.cont = div;

        var a = JSON2.parse(GM_getValue ('ThroneHistory_'+getServerId(), '[]'));
        if (matTypeof(a) == 'array') t.log = a;
        var a = JSON2.parse(GM_getValue ('ThroneSalvageHistory_'+getServerId(), '[]'));
        if (matTypeof(a) == 'array') t.SalvageLog = a;

        ThroneDelItems = ById('pbsalvage_run');
        if (Options.ThroneDeleteItems == false) {
            if (ThroneDelItems) ThroneDelItems.value = culang.throneStuffAutoSalvage+" = "+culang.buttonOFF;
        } else {
            if (ThroneDelItems) ThroneDelItems.value = culang.throneStuffAutoSalvage+" = "+culang.buttonON;
            t.timersalvage=setTimeout(t.salvageCheck,60000);
        }

        var main = '<TABLE align=center><TR><TD><INPUT class=ksSubtab ID=ptmrchSubSal type=submit value="'+culang.throneStuffSalvage+'"></td>';
        main +='<TD><INPUT class=ksSubtab ID=ptmrchSubUE type=submit value="'+culang.throneStuffUpgradeEnhance+'"></td><TD><INPUT class=ksSubtab ID=ptmrchSubRE type=submit value="'+culang.throneStuffRepair+'"></td>';
        main +='<TD><INPUT class=ksSubtab ID=ptmrchSubST type=submit value="'+culang.throneStuffStats+'"></td><TD><INPUT class=ksSubtab ID=ptmrchSubEQ type=submit value="'+culang.throneStuffEquip+'"></td>';
        main +='<td><INPUT class=ksSubtab ID=ptThroneChance type=submit value="'+culang.throneChance+'"></td>';
        main +='</tr></table>';
        main +='<DIV id=ThroneOutput style="max-height:'+(Options.HauteurBoite-130)+'px; overflow-y:auto"></div>';

        t.cont.innerHTML = main;
        t.Overv = document.getElementById('ThroneOutput');

        document.getElementById('ptmrchSubSal').addEventListener('click', e_butSubtab, false);
        document.getElementById('ptmrchSubUE').addEventListener('click', e_butSubtab, false);
        document.getElementById('ptmrchSubST').addEventListener('click', e_butSubtab, false);
        document.getElementById('ptmrchSubEQ').addEventListener('click', e_butSubtab, false);
        document.getElementById('ptmrchSubRE').addEventListener('click', e_butSubtab, false);
        document.getElementById('ptThroneChance').addEventListener('click', t.throneChance, false);
        changeSubtab (document.getElementById('ptmrchSubUE'));

        function e_butSubtab (evt){
            changeSubtab (evt.target);
        }

        function changeSubtab (but){
            if (but == t.curTabBut)
                return;
            if (t.curTabBut){
                t.curTabBut.className='ksSubtab';
                t.curTabBut.disabled=false;
            }
            t.curTabBut = but;
            but.className='ksSubtab ksSubtabSel';
            but.disabled=true;
            t.curTabName = but.id.substr(9);
            Options.curMarchTab = t.curTabName;
            t.show ();
        }
        t.checkUpgradeInfo(true);
        if (ThroneOptions.Active) t.setActionTimer = setInterval(t.doAction,10000);

    },

    throneChance: function() {
        var t = Tabs.ThroneStuff;
        
        function calc(ue, item, level, H) {
            var C = {
                "0": 0,
                "1VL": 0.005,
                "2VL": 0.0175,
                "3VL": 0.035,
                "4VL": 0.0575,
                "5VL": 0.085,
                "1L": 0.1175,
                "2L": 0.155,
                "3L": 0.1975,
                "1ML": 0.245,
                "2ML": 0.2975,
                "3ML": 0.355,
                "1M": 0.4175,
                "2M": 0.485,
                "3M": 0.5575,
                "1MH": 0.635,
                "2MH": 0.7175,
                "1H": 0.805,
                "2H": 0.8975,
                "1EH": 0.9725,
                "2EH": 1
            };
            var z = C[uW.cm.thronestats[ue][level]["Base"]];    
            var A = 1;
            if (uW.cm.WorldSettings.getSettingAsObject("TR_BUFF_ITEM_MODIFIERS")[H]) {
                A = +uW.cm.WorldSettings.getSettingAsObject("TR_BUFF_ITEM_MODIFIERS")[H]["Chance"] || 1;
            }
            var y = 0;
            if (H && H > 0) {
                y += A - 1;
            }
            y += uW.cm.HeatUpModel.getModifierPercentage() + Seed.tech.tch17 / 100;
            y = (z * y) / (1 - z);
            var min = Math.min(y, 1);
            min = Math.round(min * 10000) / 100;
            return min;
        }
    
        if(t.viewstats == null)
            t.viewstats = new CPopup ('pbviewthronestats', 0, 0, 700, 800, true);
        t.viewstats.centerMe (mainPop.getMainDiv());
        //Grundwerte
        var e = [
            uW.g_js_strings.throneRoom.common,
            uW.g_js_strings.throneRoom.uncommon,
            uW.g_js_strings.throneRoom.rare,
            uW.g_js_strings.throneRoom.epic,
            uW.g_js_strings.throneRoom.wondrous,
        ];
        var z = [{
            id: 0,
            name: uW.g_js_strings.throneRoom.buff_none,
        }, uW.ksoItems["20001"], uW.ksoItems["20002"], uW.ksoItems["20003"],
        uW.ksoItems["20004"]];
        var n = [{
            id: 0,
            name: uW.g_js_strings.throneRoom.buff_none,
        }, uW.ksoItems["20001"], uW.ksoItems["20002"], uW.ksoItems["20005"], uW.ksoItems["20006"]];

        var m= '';
        m += '<TABLE class=pdxTab>';
        m += "<tr>";
        m += '<td colspan=3><b style="color:maroon;">'+culang.viewThroneStatsAdd+'</b></td>';
        m += "</tr>";
        m += "<tr>";
        m += '<td>'+uW.techcost.tch17[0]+':&nbsp;&nbsp;</td>';
        m += '<td>'+Seed.tech.tch17 / 100+'%</td>';        
        m += '<td>(max 0.12%)</td>';    
        m += "</tr>";
        m += "<tr>";
        m += '<td>'+uW.g_js_strings.throneRoom.activity_bonus+':&nbsp;&nbsp;</td>';
        m += '<td>'+(Math.round(uW.cm.HeatUpModel.getModifierPercentage() * 100) / 100)+'%</td>';
        m += '<td>(max 0.15%)</td>';    
        m += "</tr>";
        m += '</table>';
        m += '<br><br>';
        m += '<TABLE width="100%" class=pdxTab>';
        m += "<tr>";
        m += '<td colspan=13><b style="color:maroon;">'+culang.viewThroneStatsUpgrade+'</b></td>';
        m += "</tr>";
        m += "<tr>";
        m += '<td>&nbsp;</td>';
        for (var i = 1; i<13; i++) m+= '<td style="text-align:center;"><b>+'+i+'</b></td>';
        for (var buff = 0; buff < n.length; buff++) {
            m += "<tr>";
            m += '<td>'+n[buff].name+'</td>';    
            for (var i = 1; i<13; i++) {
                m+= '<td style="text-align:center;">'+calc("upgrade",buff, i, n[buff].id)+'%</td>';
            }
            m += "</tr>";        
        }
        m +='</table>';
        m +='<br><br>';
        m += '<TABLE width="100%" class=pdxTab>';
        m += "<tr>";
        m += '<td colspan=13><b style="color:maroon;">'+culang.viewThroneStatsEnhance+'</b></td>';
        m += "</tr>";
        m += "<tr>";
        m += '<td>&nbsp;</td>';
        for (var i = 0; i<5; i++) m+= '<td style="text-align:center;"><b>'+e[i]+'</b></td>';
        for (var buff = 0; buff < z.length; buff++) {
            m += "<tr>";
            m += '<td>'+z[buff].name+'</td>';    
            for (var i = 0; i<5; i++) {
                m+= '<td style="text-align:center;">'+calc("enhance",buff, i+1, z[buff].id)+'%</td>';
            }
            m += "</tr>";        
        }
        m +='</table>';
        m +='<br><br>';
        m +='<div style="text-align:center;"><input type="submit" value="'+culang.viewThroneStatsCalc+'" id="pbThroneStatsCalc"></div>';
        m +='<br><br>';
        m +='<div>'+culang.viewThroneStatsHint+'</div>';
        t.viewstats.getMainDiv().innerHTML = m;
        t.viewstats.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.viewThroneStats+'</div>';
        t.viewstats.show(true);
        ById("pbThroneStatsCalc").addEventListener ('click', function (){
            t.throneChance();
        }, false);            
        
    },

    Salvage : function (){
        var t = Tabs.ThroneStuff;
        try {
            var effects = uW.cm.thronestats.effects;
            m = '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffSalvageHead+'</div><TABLE width=100%><TR>';

            m+='<TD>';
            m+='<div style="margin-top: 0px;"><INPUT type=submit id=pbsalvage_run value="'+culang.throneStuffAutoSalvage+' = '+(Options.ThroneDeleteItems?''+culang.buttonON+'':''+culang.buttonOFF+'')+'" /></div>';
            m+='<div style="margin-top: 2px; padding-left: 11px;">'+culang.mainIntervall+': <input type=text size=3 id=KsThroneInterval value="'+ThroneOptions.IntervalMin+'" > '+culang.mainMinutes+"</div>";
            m+='<div style="margin-top: 4px;"><INPUT type=submit id=pbsalvage_preview value="'+culang.mainShow+'" /></div>'
            m+='</td>';

            m+='<TD>';
            m+='<div style="margin-top: 2px;">'+culang.throneStuffSalvageKeepFirst+' <INPUT type=text id=SaveXitems size=2 maxlength=2 value='+ ThroneOptions.SalvageV2.SaveXitems +'> '+culang.throneStuffSalvageKeepFirst2+"</div>";
            m+='<div style="margin-top: 2px;">'+culang.throneStuffSalvageKeepSel+' ' + htmlSelector({0:culang.mainNone, 1:unsafeWindow.g_js_strings.throneRoom.common, 2:unsafeWindow.g_js_strings.throneRoom.uncommon, 3:unsafeWindow.g_js_strings.throneRoom.rare, 4:unsafeWindow.g_js_strings.throneRoom.epic, 5:unsafeWindow.g_js_strings.throneRoom.wondrous},ThroneOptions.SalvageV2.QualityFilter,'id=Quality')+' '+culang.throneStuffSalvageKeepSel2+'</div>';
            m+='<div style="margin-top: 2px;">'+culang.throneStuffSalvageKeepFam
                +' <input type=checkbox id=KsSType_advisor '+ (ThroneOptions.SalvageV2.TypeFilter.Advisor?'CHECKED ':'') +'>advisor '
                +'<input type=checkbox id=KsSType_banner '+ (ThroneOptions.SalvageV2.TypeFilter.Banner?'CHECKED ':'') +'> banner '
                +'<input type=checkbox id=KsSType_chair '+ (ThroneOptions.SalvageV2.TypeFilter.Chair?'CHECKED ':'') +'> chair '
                +'<input type=checkbox id=KsSType_table '+ (ThroneOptions.SalvageV2.TypeFilter.Table?'CHECKED ':'') +'> table'
                +'<input type=checkbox id=KsSType_window '+ (ThroneOptions.SalvageV2.TypeFilter.Window?'CHECKED ':'') +'> window '
                +'<input type=checkbox id=KsSType_trophy '+ (ThroneOptions.SalvageV2.TypeFilter.Trophy?'CHECKED ':'') +'> trophy '
                +'<input type=checkbox id=KsSType_candelabrum '+ (ThroneOptions.SalvageV2.TypeFilter.Candelabrum?'CHECKED ':'') +'> candelabrum '
                +culang.throneStuffSalvageKeepFam2+'</div>';
            m+='<div style="margin-top: 2px;">'+'<input type=checkbox id=DeleteXitemsEnabled '+ (ThroneOptions.SalvageV2.DeleteXitems.IsEnabled?'CHECKED ':'') +'/>'+' '+culang.throneStuffSalvageLastXItems+''+' <INPUT type=text id=DeleteXitems size=2 maxlength=2 value='+ ThroneOptions.SalvageV2.DeleteXitems.Value +'> '+''+culang.throneStuffSalvageLastXItems2+''+' '+''+culang.throneStuffSalvageLastXItemsNote+''+"</div>";
            m+='<div style="margin-top: 2px;">'+'<input type=checkbox id=DeleteP1Enabled '+ (ThroneOptions.SalvageV2.LevelP1?'CHECKED ':'') +'/>'+' '+culang.throneStuffSalvageP1+"</div>";
            m+='<div style="margin-top: 2px;">'+'<input type=checkbox id=DeleteCityMin '+ (ThroneOptions.SalvageV2.CityMin?'CHECKED ':'') +'/>'+' '+culang.throneStuffSalvageCM+"</div>";
            m+='</td>';

            m+='<TD>';
            m+='<INPUT id=ShowSalvageHistory type=submit value="'+culang.throneStuffSalvageHistory+'"></td></tr><tr><td colspan=3><sup><span class=boldRed>'+culang.mainImportant+'</span>:</sup> <span class="helpText">'+culang.throneStuffSalvageKeepNote+'</span></table>'
            m+='<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffSalvageKeep+'</div>';
            m+='</td>';
            
            m+='<div style="margin-top: 2px;margin-left: 16px;"> A: '+ htmlSelector({100:"---", 0:culang.throneStuffSalvageKeepEffects1, 2:culang.throneStuffSalvageKeepEffects2, 4:culang.throneStuffSalvageKeepEffects3, 7:culang.throneStuffSalvageKeepEffects4, 8:culang.throneStuffSalvageKeepEffects5},ThroneOptions.SalvageV2.EffectMode,'id=SalvageEffectMode1')+
            '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; % Filter:'+'</div>';
            m+='<div style="margin-top: 2px;margin-left: 16px;"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;B: '+ htmlSelector({100:"---", 0:culang.throneStuffSalvageKeepEffects1, 2:culang.throneStuffSalvageKeepEffects2, 4:culang.throneStuffSalvageKeepEffects3, 7:culang.throneStuffSalvageKeepEffects4, 8:culang.throneStuffSalvageKeepEffects5},ThroneOptions.SalvageV2.EffectMode2,'id=SalvageEffectMode2')+'</div>';
            m+='<div style="margin-top: 2px;margin-left: 16px;"> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;C: '+ htmlSelector({100:"---", 0:culang.throneStuffSalvageKeepEffects1, 2:culang.throneStuffSalvageKeepEffects2, 4:culang.throneStuffSalvageKeepEffects3, 7:culang.throneStuffSalvageKeepEffects4, 8:culang.throneStuffSalvageKeepEffects5},ThroneOptions.SalvageV2.EffectMode3,'id=SalvageEffectMode3')+'</div>';

            m+='<TABLE width=80% class="pdxTab"><tr style="background-Color:#aaa;text-align:left">';
            m+='<td>&nbsp;</td>';
            m+='<td><b> [A] &nbsp; [B] &nbsp; [C] &nbsp; '+culang.buttonSave+'</b></td>';
            m+='<td>&nbsp;</td>';
            m+='<td><b>'+''+culang.shortMin+' %'+'</b></td>';
            m+='<td>advisor banner chair table window trophy c.brum (%)</td>';
            m+='<td><b>'+culang.throneFamily+'</b></td>';
            m+='</tr>';

            for (iEffektId in effects){
                if (typeof(effects[iEffektId]) == "undefined") continue;
                if (typeof(effects[iEffektId][1]) == "undefined") continue;
                if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId]) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId]={IsEnabled:false,Percent:'',PercentAdvisor:'',PercentBanner :'',PercentChair  :'',PercentTable  :'',PercentWindow :'',PercentTrophy :'',PercentCandelabrum :'',};
                if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentAdvisor) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentAdvisor='';
                if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentBanner ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentBanner ='';
                if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentChair  ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentChair  ='';
                if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTable  ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTable  ='';
                if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentWindow ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentWindow ='';
                if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTrophy ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTrophy ='';                
                if (typeof(ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentCandelabrum ) == "undefined") ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentCandelabrum ='';            
                m+='<tr>';
                m+='<td >&nbsp;</td>';
                m+='<td>'+
                    '<INPUT class='+iEffektId+' id="KsS1_'+iEffektId+'" type=checkbox ' + (ThroneOptions.SalvageV2.EffectFilter[iEffektId].IsEnabled ?'CHECKED ':'') +'/> &nbsp;'+
                    '<INPUT class='+iEffektId+' id="KsS2_'+iEffektId+'" type=checkbox ' + (ThroneOptions.SalvageV2.EffectFilter[iEffektId].IsEnabled2?'CHECKED ':'') +'/> &nbsp;'+
                    '<INPUT class='+iEffektId+' id="KsS3_'+iEffektId+'" type=checkbox ' + (ThroneOptions.SalvageV2.EffectFilter[iEffektId].IsEnabled3?'CHECKED ':'') +'/> &nbsp;'+
                    effects[iEffektId][1]+'</td>';
                m+='<td>&nbsp;</td>';
                m+='<td>'+'<INPUT class='+iEffektId+' id="KsSP_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].Percent+'" style="width: 40px;"/>%'+'</td>';
                m+='<td>';
                // % for advisor banner chair table window trophy candelabrum
                m+='<INPUT class='+iEffektId+' id="KsSPAd_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentAdvisor+'" style="width: 32px;"/>'
                m+='<INPUT class='+iEffektId+' id="KsSPBa_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentBanner +'" style="width: 32px;"/>'
                m+='<INPUT class='+iEffektId+' id="KsSPCh_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentChair  +'" style="width: 32px;"/>'
                m+='<INPUT class='+iEffektId+' id="KsSPTa_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTable  +'" style="width: 32px;"/>'
                m+='<INPUT class='+iEffektId+' id="KsSPWi_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentWindow +'" style="width: 32px;"/>'
                m+='<INPUT class='+iEffektId+' id="KsSPTr_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentTrophy +'" style="width: 32px;"/>'
                m+='<INPUT class='+iEffektId+' id="KsSPCa_'+iEffektId+'" maxlength=4 type=input value="'+ ThroneOptions.SalvageV2.EffectFilter[iEffektId].PercentCandelabrum +'" style="width: 32px;"/>'
                m+='</td>';
                //family
                m+='<td>'+effects[iEffektId]["2"] +'</td>';
                m+='</tr>';
            }

            m+='</table>';
            
            //m+='<pre>'+inspect(effects,4)+'</pre>';
            t.Overv.innerHTML = m;
            
            if (parseIntNan(ById("KsThroneInterval").value)<3) ById("KsThroneInterval").value=3;
            ById("KsThroneInterval").addEventListener('change', function(e){
                if (parseIntNan(ById("KsThroneInterval").value)<3) ById("KsThroneInterval").value=3;
                ThroneOptions.IntervalMin=ById("KsThroneInterval").value;
                saveThroneOptions();
            },false);

            ById("KsSType_advisor").addEventListener('click', function(e){
                ThroneOptions.SalvageV2.TypeFilter.Advisor=ById("KsSType_advisor").checked;saveThroneOptions();
            },false);
            ById("KsSType_banner").addEventListener('click', function(e){
                ThroneOptions.SalvageV2.TypeFilter.Banner=ById("KsSType_banner").checked;saveThroneOptions();
            },false);
            ById("KsSType_chair").addEventListener('click', function(e){
                ThroneOptions.SalvageV2.TypeFilter.Chair=ById("KsSType_chair").checked;saveThroneOptions();
            },false);
            ById("KsSType_table").addEventListener('click', function(e){
                ThroneOptions.SalvageV2.TypeFilter.Table=ById("KsSType_table").checked;saveThroneOptions();
            },false);
            ById("KsSType_window").addEventListener('click', function(e){
                ThroneOptions.SalvageV2.TypeFilter.Window=ById("KsSType_window").checked;saveThroneOptions();
            },false);
            ById("KsSType_trophy").addEventListener('click', function(e){
                ThroneOptions.SalvageV2.TypeFilter.Trophy=ById("KsSType_trophy").checked;saveThroneOptions();
            },false);
            ById("KsSType_candelabrum").addEventListener('click', function(e){
                ThroneOptions.SalvageV2.TypeFilter.Candelabrum=ById("KsSType_candelabrum").checked;saveThroneOptions();
            },false);

            ById("pbsalvage_run").addEventListener('click', function(e){t.toggleSalvage();},false);
            ById("pbsalvage_preview").addEventListener('click', function(e){t.previewSalvage();},false);
            ById('SalvageEffectMode1').addEventListener ('change', function(){
                ThroneOptions.SalvageV2.EffectMode = document.getElementById('SalvageEffectMode1').value;
                saveThroneOptions();
            },false);
            ById('SalvageEffectMode2').addEventListener ('change', function(){
                ThroneOptions.SalvageV2.EffectMode2 = document.getElementById('SalvageEffectMode2').value;
                saveThroneOptions();
            },false);
            ById('SalvageEffectMode3').addEventListener ('change', function(){
                ThroneOptions.SalvageV2.EffectMode3 = document.getElementById('SalvageEffectMode3').value;
                saveThroneOptions();
            },false);

            for (iEffektId in effects){
                if (typeof(effects[iEffektId]) == "undefined") continue;
                ById('KsSP_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].Percent = ById('KsSP_'+e.target['className']).value;
                    saveThroneOptions();
                },false);
                ById('KsSPAd_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentAdvisor = ById('KsSPAd_'+e.target['className']).value;
                    saveThroneOptions();
                },false);
                ById('KsSPBa_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentBanner = ById('KsSPBa_'+e.target['className']).value;
                    saveThroneOptions();
                },false);
                ById('KsSPCh_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentChair = ById('KsSPCh_'+e.target['className']).value;
                    saveThroneOptions();
                },false);
                ById('KsSPTa_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentTable = ById('KsSPTa_'+e.target['className']).value;
                    saveThroneOptions();
                },false);
                ById('KsSPWi_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentWindow = ById('KsSPWi_'+e.target['className']).value;
                    saveThroneOptions();
                },false);
                ById('KsSPTr_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentTrophy = ById('KsSPTr_'+e.target['className']).value;
                    saveThroneOptions();
                },false);
                ById('KsSPCa_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].PercentCandelabrum = ById('KsSPCa_'+e.target['className']).value;
                    saveThroneOptions();
                },false);
                
                ById('KsS1_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].IsEnabled = ById('KsS1_'+e.target['className']).checked;
                    saveThroneOptions();
                },false);
                ById('KsS2_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].IsEnabled2 = ById('KsS2_'+e.target['className']).checked;
                    saveThroneOptions();
                },false);
                ById('KsS3_'+iEffektId).addEventListener ('change', function(e){
                    ThroneOptions.SalvageV2.EffectFilter[e.target['className']].IsEnabled3 = ById('KsS3_'+e.target['className']).checked;
                    saveThroneOptions();
                },false);
            }
            
            document.getElementById('Quality').addEventListener  ('change', function(){ThroneOptions.SalvageV2.QualityFilter = this.value;saveThroneOptions();},false);
            document.getElementById('ShowSalvageHistory').addEventListener('click', function(){t.PaintSalvageHistory()} , false);
            document.getElementById('SaveXitems').addEventListener('change', function(){ThroneOptions.SalvageV2.SaveXitems = document.getElementById('SaveXitems').value;saveThroneOptions();} , false);
            document.getElementById('DeleteXitemsEnabled').addEventListener('change', function(){ThroneOptions.SalvageV2.DeleteXitems.IsEnabled = document.getElementById('DeleteXitemsEnabled').checked;saveThroneOptions();} , false);
            document.getElementById('DeleteP1Enabled').addEventListener('change', function(){
                ThroneOptions.SalvageV2.LevelP1 = document.getElementById('DeleteP1Enabled').checked;
                saveThroneOptions();
            } , false);
            document.getElementById('DeleteCityMin').addEventListener('change', function(){
                ThroneOptions.SalvageV2.CityMin = document.getElementById('DeleteCityMin').checked;
                saveThroneOptions();
            } , false);
            document.getElementById('DeleteXitems').addEventListener('change', function(){
                if(parseIntNan(document.getElementById('DeleteXitems').value)<2)document.getElementById('DeleteXitems').value=2;
                ThroneOptions.SalvageV2.DeleteXitems.Value = document.getElementById('DeleteXitems').value;saveThroneOptions();
            }, false);

        } catch (ex) {
            t.Overv.innerHTML = '<PRE>'+ ex.name +': '+ ex.message +'</pre>';
        }
    },
    toggleSalvage:function() {
        var t = Tabs.ThroneStuff;
        if(Options.ThroneDeleteItems){
            if(ById("pbsalvage_run")) ById("pbsalvage_run").value = culang.throneStuffAutoSalvage+" = "+culang.buttonOFF;
            Options.ThroneDeleteItems = false;
            saveOptions();saveThroneOptions();
            clearTimeout(t.timersalvage);
        } else {
            if (ById("pbsalvage_run")) ById("pbsalvage_run").value = culang.throneStuffAutoSalvage+" = "+culang.buttonON;
            Options.ThroneDeleteItems = true;
            t.SalvageRunning=false;
            t.SalvageArray=[];
            t.SalvageArrayP1=[];
            t.LastDeleted=0;
            t.salvageCheck();
            saveOptions();saveThroneOptions();
        }
    },

    previewSalvage:function() {
        // <summary> Handler of Salvage Preview Button </summary>
        var t = Tabs.ThroneStuff;
        if(Options.ThroneDeleteItems) {
            clearTimeout(t.timersalvage);
            t.toggleSalvage();
        }
        t.SalvagePreviewMode=true;
        t.salvageCheck();
        t.SalvagePreviewMode=false;
    },
    Upgrade_Enhance :function (){
        var t = Tabs.ThroneStuff;
        //try {
        var m = '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffEUHead+'</div><TABLE width=100% height=0% class=pdxTab><TR align="center">';
        if (ThroneOptions.Active == false) {
            m += '<TD><INPUT id=Enable type=submit value="'+culang.throneStuffEUQueueEnable+' = '+culang.buttonOFF+'"></td>';
        } else {
            m += '<TD><INPUT id=Enable type=submit value="'+culang.throneStuffEUQueueEnable+' = '+culang.buttonON+'"></td>';
        }
        m += '<TD><INPUT id=ShowHistory type=submit value="'+culang.throneStuffEUQueueHistory+'"></td>';
        m += '<td style="text-align:left;"><input type=checkbox id=CitySelMax '+ (ThroneOptions.CityMax?'CHECKED ':'') +'/>'+' '+culang.throneStuffCityMax+"</td></tr>";
        //m += '<tr><td></td><td></td><td style="text-align:left;">';
        //m += '<input type=checkbox id=ThroneRepairAll '+ (ThroneOptions.RepairAll?'CHECKED ':'') +'/>'+' '+culang.throneStuffRepairAll;
        //m += '</td></tr>';
        m += '<tr><td></td><td></td><td style="text-align:left;">';
        m += '<input type=checkbox id=Throne20001 '+ (ThroneOptions.i20001?'CHECKED ':'') +'> ';
        m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20001.jpg" width=40 title="'+uW.itemlist.i20001.name+' - '+uW.itemlist.i20001.description+'">&nbsp;&nbsp;';
        m += '<input type=checkbox id=Throne20002 '+ (ThroneOptions.i20002?'CHECKED ':'') +'> ';
        m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20002.jpg" width=40 title="'+uW.itemlist.i20002.name+' - '+uW.itemlist.i20002.description+'">&nbsp;&nbsp;';
        m += '<input type=checkbox id=Throne20005 '+ (ThroneOptions.i20005?'CHECKED ':'') +'> ';
        m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20005.jpg" width=40 title="'+uW.itemlist.i20005.name+' - '+uW.itemlist.i20005.description+'">&nbsp;&nbsp;';
        m += '<input type=checkbox id=Throne20006 '+ (ThroneOptions.i20006?'CHECKED ':'') +'> ';
        m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20006.jpg" width=40 title="'+uW.itemlist.i20006.name+' - '+uW.itemlist.i20006.description+'">&nbsp;&nbsp;';
        m += '<input type=checkbox id=Throne20004 '+ (ThroneOptions.i20004?'CHECKED ':'') +'> ';
        m += '<img src="http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/20004.jpg" width=40 title="'+uW.itemlist.i20004.name+' - '+uW.itemlist.i20004.description+'">';
        m += '</td></tr>';
        m+= '</tr></table><DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffEUQueueAdd+'</div><TABLE class=pdxTab><br/>';
        m+='<TR><TD>'+culang.throneStuffEUQueueThroneItems+'<br><br><SELECT id=ThroneItems type=list>';
        
        var nb=0,couleur=0;
        for (i in unsafeWindow.kocThroneItems){
            nb++
            var styleee="background-color:#FFF";
            if (unsafeWindow.kocThroneItems[i].isEquipped) {
                styleee="background-color:#99DC99";
                if (nb==1) couleur=1;
            }else if (unsafeWindow.kocThroneItems[i].isBroken) {
                styleee="background-color:#DC9999";
            }

            if (nb>(parseInt(Seed.throne.rowNum)*5)) break;
            var faction=unsafeWindow.kocThroneItems[i].faction;
            var type=unsafeWindow.kocThroneItems[i].type;
            if(faction=="briton")faction="britton";//Kabam bug workaround
            var imagesrc='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/'+faction+'/'+faction+'_'+type+'_normal_1.png'; 
            m+="<option style='"+styleee+"' value="+unsafeWindow.kocThroneItems[i]["id"]+"> "+(nb<10?"&nbsp;&nbsp;":"")+nb+". "+getThroneItemName(i)+"</option>";
        }

        m+='</select>'
        m+='<br><br>'
        m+='<INPUT id=addEnhance type=submit value="'+culang.throneStuffEnhance+'">';
        m+='<INPUT id=addUpgrade type=submit value="'+culang.throneStuffUpgrade+'">';
        m+='</td>';
        m+='<TD><DIV id=ShowHoover></div></td>';
        m+='</tr></table><br/>';
        m+= '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffHeadStats+'</div>';
        m+= '<br/><DIV id=ShowStatus></div></p>';
        m+= '<DIV id=ShowTries></div><br/>';
        m+= '<DIV id=ShowStones></div><br/>';
        m+= '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffHeadUpgradeInfo+'</div>';
        m+= '<br/><DIV id=ShowInfo></div><br/>';
        m+= '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffHeadQueue+'</div>';
        m+= '<br/><DIV id=ShowQueueDiv></div>';
        t.Overv.innerHTML = m;
        if (couleur==1) ById("ThroneItems").style.backgroundColor="#99DC99"
        document.getElementById('CitySelMax').addEventListener('change', function(){
            ThroneOptions.CityMax = document.getElementById('CitySelMax').checked;
            saveThroneOptions();
        } , false);
        document.getElementById('Throne20001').addEventListener('change', function(){
            ThroneOptions.i20001 = document.getElementById('Throne20001').checked;
            saveThroneOptions();
        } , false);
        document.getElementById('Throne20002').addEventListener('change', function(){
            ThroneOptions.i20002 = document.getElementById('Throne20002').checked;
            saveThroneOptions();
        } , false);
        document.getElementById('Throne20004').addEventListener('change', function(){
            ThroneOptions.i20004 = document.getElementById('Throne20004').checked;
            saveThroneOptions();
        } , false);
        document.getElementById('Throne20005').addEventListener('change', function(){
            ThroneOptions.i20005 = document.getElementById('Throne20005').checked;
            saveThroneOptions();
        } , false);
        document.getElementById('Throne20006').addEventListener('change', function(){
            ThroneOptions.i20006 = document.getElementById('Throne20006').checked;
            saveThroneOptions();
        } , false);
        /*
        document.getElementById('ThroneRepairAll').addEventListener('change', function(){
            ThroneOptions.RepairAll = document.getElementById('ThroneRepairAll').checked;
            saveThroneOptions();
        } , false);
        */
        document.getElementById('addEnhance').addEventListener ('click', function (){t.addToQueue(document.getElementById('ThroneItems').value,""+culang.throneStuffEnhance+"");},false);
        document.getElementById('addUpgrade').addEventListener ('click', function (){t.addToQueue(document.getElementById('ThroneItems').value,""+culang.throneStuffUpgrade+"");},false);
        document.getElementById('ThroneItems').addEventListener ('change', function (){t.paintHoover();},false);
        document.getElementById('Enable').addEventListener('click', function(){t.toggleThroneState()} , false);
        document.getElementById('ShowHistory').addEventListener('click', function(){t.PaintHistory()} , false);

        if (ThroneOptions.Items.length ==0 && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoItems+"</i>";
        else {
            if (ThroneOptions.Active && Seed.queue_throne.end == undefined && ById('ShowStatus')) document.getElementById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueWaiting+"</i>";
            if (ThroneOptions.Active && Seed.queue_throne.end != undefined && ById('ShowStatus')) t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
            if (!ThroneOptions.Active && Seed.queue_throne.end != undefined && ById('ShowStatus')) t.setRepairTimer = setInterval (t.repairTimerUpdate,1000);
            if (!ThroneOptions.Active && Seed.queue_throne.end == undefined && ById('ShowStatus')) document.getElementById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
        }
        if (ThroneOptions.Tries > 0) document.getElementById('ShowTries').innerHTML = ""+culang.throneStuffEUQueueShowTries+" " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;
        else document.getElementById('ShowTries').innerHTML = ""+culang.throneStuffEUQueueShowTriesNone+"";
        if (ThroneOptions.Items.length>0) { // && ThroneOptions.Tries > 0) {
            t.PaintQueue();
            t.paintInfo();

        }
        t.paintStones();
        t.paintHoover();
        setInterval(t.paintStones,30000);
    },
    Equip :function (){
        var t = Tabs.ThroneStuff;
        try {
            var m = '<DIV id=pbTowrtDivF class=pdxStat>'+culang.throneStuffEquipHead+'</div><br>';
            m+='<DIV align=center>'+culang.throneStuffEquipPreset+' <SELECT id=preset type=list></select></div><br><TABLE width=100% height=0% class=pdxTab>';
            for (k in t.EquipType){
                var y = t.EquipType[k];
                if (typeof(y) == "string") {
                    what = y.toLowerCase();
                    if (y == "Windows") y = "Window";
                    m+='<TR><TD>'+ y +':</td><TD></td><TD><SELECT id='+ what +' type=list></select></td><TD><INPUT id="Equip'+ what +'" type=submit value="'+culang.throneStuffEquip+'"></td><TD><INPUT id="Unequip'+ what +'" type=submit value="'+culang.throneUnequipItem+'"></td><TD><div id="info'+ what +'"</td></tr><TR><TD>&nbsp;</td></tr><TR><TD>&nbsp;</td></tr>';
                }
            }
            m+="</table>"
            t.Overv.innerHTML = m;
            document.getElementById("preset").options.length=0;
            for (i=1;i<=Seed.throne.slotNum;i++){
                var o = document.createElement("option");
                o.text = i;
                o.value = i;
                document.getElementById("preset").options.add(o);
            }
            document.getElementById("advisor").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("advisor").value,"advisor")},false);
            document.getElementById("banner").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("banner").value,"banner")},false);
            document.getElementById("chair").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("chair").value,"chair")},false);
            document.getElementById("table").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("table").value,"table")},false);
            document.getElementById("windows").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("windows").value,"windows")},false);
            document.getElementById("trophy").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("trophy").value,"trophy")},false);
            document.getElementById("candelabrum").addEventListener ('change', function (){t.paintEquipInfo(document.getElementById("candelabrum").value,"candelabrum")},false);
            
            document.getElementById("Equipadvisor").addEventListener ('click', function (){t.doEquip(document.getElementById("advisor").value)},false);
            document.getElementById("Equipbanner").addEventListener ('click', function (){t.doEquip(document.getElementById("banner").value)},false);
            document.getElementById("Equipchair").addEventListener ('click', function (){t.doEquip(document.getElementById("chair").value)},false);
            document.getElementById("Equiptable").addEventListener ('click', function (){t.doEquip(document.getElementById("table").value)},false);
            document.getElementById("Equipwindows").addEventListener ('click', function (){t.doEquip(document.getElementById("windows").value)},false);
            document.getElementById("Equiptrophy").addEventListener ('click', function (){t.doEquip(document.getElementById("trophy").value)},false);
            document.getElementById("Equipcandelabrum").addEventListener ('click', function (){t.doEquip(document.getElementById("candelabrum").value)},false);
            
            document.getElementById("Unequipadvisor").addEventListener ('click', function (){t.doUnequip(document.getElementById("advisor").value)},false);
            document.getElementById("Unequipbanner").addEventListener ('click', function (){t.doUnequip(document.getElementById("banner").value)},false);
            document.getElementById("Unequipchair").addEventListener ('click', function (){t.doUnequip(document.getElementById("chair").value)},false);
            document.getElementById("Unequiptable").addEventListener ('click', function (){t.doUnequip(document.getElementById("table").value)},false);
            document.getElementById("Unequipwindows").addEventListener ('click', function (){t.doUnequip(document.getElementById("windows").value)},false);
            document.getElementById("Unequiptrophy").addEventListener ('click', function (){t.doUnequip(document.getElementById("trophy").value)},false);
            document.getElementById("Unequipcandelabrum").addEventListener ('click', function (){t.doUnequip(document.getElementById("candelabrum").value)},false);

            document.getElementById("preset").addEventListener ('change', function (){t.doPreset(document.getElementById("preset").value)},false);
            document.getElementById("preset").value = Seed.throne.activeSlot;
            t.FillEquipCheckboxes();
        } catch (ex) {
            t.Overv.innerHTML = '<PRE>'+ ex.name +' : '+ ex.message +'</pre>';
        }
    },

    FillEquipCheckboxes: function(){
        var t = Tabs.ThroneStuff;
        for (k in t.EquipType) {
            var y = t.EquipType[k];
            var itemEquiped = 0;
            var count = 0;
            if (typeof(y) == "string") {
                what = y.toLowerCase();
                document.getElementById(what).options.length=0;
                for (l in unsafeWindow.kocThroneItems) {
                    effects = unsafeWindow.kocThroneItems[l];
                    check = what;
                    if (check == "windows") check = "window";
                    count++;
                    if (count<=(parseInt(Seed.throne.rowNum)*5)){
                        if (effects.type == check && effects.isBroken==false) {
                            var o = document.createElement("option");
                            o.text = getThroneItemName(l);
                            o.value = l;
                            document.getElementById(what).options.add(o);
                            if (effects.isEquipped) itemEquiped = l;
                        }
                    }

                }
                if (document.getElementById(what).options.length == 0){
                    var o = document.createElement("option");
                    o.text = ""+culang.throneStuffEquipNoItemsAvailable+" " + check + " "+culang.throneStuffEquipNoItemsAvailable2+"";
                    o.value = 1;
                    document.getElementById(what).options.add(o);
                    itemEquiped = 1;
                } else if (itemEquiped == 0) {
                    var o = document.createElement("option");
                    o.text = ""+culang.throneStuffEquipNoItems+" " + check + " "+culang.throneStuffEquipNoItems2+"";
                    o.value = 2;
                    document.getElementById(what).options.add(o);
                    document.getElementById('info'+what).innerHTML = "";
                    itemEquiped = 2;
                }
                //logit(what + ' / ' + itemEquiped);
                document.getElementById(what).value = itemEquiped;
            }

            switch(itemEquiped){
                case 0:
                    break;
                case 1:
                    document.getElementById("Equip"+what).disabled = true;
                    document.getElementById("Unequip"+what).disabled = true;
                    break;
                case 2:
                    document.getElementById("Equip"+what).disabled = false;
                    document.getElementById("Unequip"+what).disabled = true;
                    break;
                default:
                    document.getElementById("Equip"+what).disabled = true;
                    document.getElementById("Unequip"+what).disabled = false;
                    t.paintEquipInfo(ById(what).value,what);
                    break;
            }

        }
    },

    doPreset : function (preset){
        var t = Tabs.ThroneStuff;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'setPreset';
        params.presetId = preset;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                    button = '<li id="throneInventoryPreset' + preset + '" class="active">'+preset+'</li>';
                    unsafeWindow.cm.ThroneView.clickActivePreset(button);
                    t.FillEquipCheckboxes();
                }
            },
            onFailure: function () {
                return;
            },
        });

    },

    paintEquipInfo : function (z,what){
        var t = Tabs.ThroneStuff;
        var m="";
        if (typeof(unsafeWindow.kocThroneItems[z]) == 'object') {
            var y = unsafeWindow.kocThroneItems[z];
        } else return;
        var id =0;
        var tier=0;
        var Current=0;
        m="<TABLE width=80% height=0% align='center' class=pdxTab>";
        for (i=1;i<=5;i++) {
            id = y["effects"]["slot"+i]["id"];
            tier = parseInt(y["effects"]["slot"+i]["tier"]);
            level = y["level"];
            p = unsafeWindow.cm.thronestats.tiers[id][tier];
            Current = p.base + ((level * level + level) * p.growth * 0.5);
            var quality = parseInt(y["quality"]);
            if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
            else m+='<TR><TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
        }
        m+="</table>"

        ById('info'+what).innerHTML = m;
    },

    Stats :function (){
        var t = Tabs.ThroneStuff;
        try {
            m= '<DIV class=pdxStat>'+culang.throneStuffHeadStats+'</div><center><table border=0 width=75%><tr><td colspan=3 style="text-align:right"></td></tr>';
            var k=Seed.throne.slotEquip[Seed.throne.activeSlot]; //TODO rename k
            var B=0, w={}, x, C; //TODO rename B, w, x, C
            for (var K in k) { //TODO rename K
                var item = uW.kocThroneItems[k[K]];
                if (item) {
                    x=0;

                    for (var M in item.effects) {//TODO rename M
                        x++;
                        if (item.quality >= x) {
                            B++;
                            I = uW.cm.thronestats.effects[item.effects[M].id];
                            effects = uW.cm.thronestats.tiers[item.effects[M].id][item.effects[M].tier];
                            C = + effects.base + (item.level * item.level + item.level) * + effects.growth * 0.5;
                            // C = Math.ceil(C);
                            if (!item.isBroken) {
                                if (!w[item.effects[M].id]) {
                                    w[item.effects[M].id] = {};
                                    w[item.effects[M].id].nameitem="";
                                }
                                if (!w[item.effects[M].id].percent) {
                                    w[item.effects[M].id].percent = C;
                                } else {
                                    w[item.effects[M].id].percent += C;
                                }
                                w[item.effects[M].id].name = I[1];
                                w[item.effects[M].id].nameitem += "(" + getThroneItemName(item.id) + ")<br>";
                            }
                        }
                    }
                }
            }
            B = 0;
            for (var K in w) {
                var Current =  Math.round(w[K].percent*100)/100;
                G="<tr><td align=right><b>"+ Current + " %</b></td><td align=left>" + w[K].name + "</td><td>"+w[K].nameitem+"</td></tr>";
                m+=G;
            }
            t.Overv.innerHTML = m;
        } catch (ex) {
            t.Overv.innerHTML = '<PRE>'+ ex.name +': '+ ex.message +'</pre>';
        }
    },

    togOpt : function (checkboxId, optionName, callOnChange){
        var t = Tabs.ThroneStuff;
        var checkbox = ById(checkboxId);
        if (Options[optionName])
            checkbox.checked = true;
        checkbox.addEventListener ('change', eventHandler, false);
        function eventHandler (){
            Options[optionName] = this.checked;
            saveOptions();
            if (callOnChange)
                callOnChange (this.checked);
        }
    },

    changeOpt : function (valueId, optionName, callOnChange){
        var t = Tabs.ThroneStuff;
        var e = ById(valueId);
        e.value = Options[optionName];
        e.addEventListener ('change', eventHandler, false);
        function eventHandler (){
            Options[optionName] = this.value;
            saveOptions();
            if (callOnChange)
                callOnChange (this.value);
        }
    },

    toggleThroneState: function(){
        var t = Tabs.ThroneStuff;
        if (Options.salvageconfig.Repairrunning ==true) {
            alert(culang.throneStuffEUNotPossible);
            return;
        }
        if (ThroneOptions.Active == true) {
            ThroneOptions.Active = false;
            if(ById("Enable")) ById('Enable').value = culang.throneStuffEUQueueEnable+' = '+culang.buttonOFF;
            saveThroneOptions();
            clearTimeout(t.setActionTimer);
            if (Seed.queue_throne.end == undefined && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
        } else {
            ThroneOptions.Active = true;
            if(ById("Enable")) ById('Enable').value = culang.throneStuffEUQueueEnable+' = '+culang.buttonON;
            saveThroneOptions();
            t.setActionTimer = setInterval(t.doAction,5000);
            if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueWaiting+"</i>";
        }
    },

    _addTab: function(id,name,qualityfrom,qualityto,levelfrom,levelto,action,active,cost){
        var t = Tabs.ThroneStuff;
        var a="";
        var b="";
        switch (qualityfrom) {
            case 0:a = unsafeWindow.g_js_strings.throneRoom.simple;break;
            case 1:a = unsafeWindow.g_js_strings.throneRoom.common;break;
            case 2:a = unsafeWindow.g_js_strings.throneRoom.uncommon;break;
            case 3:a = unsafeWindow.g_js_strings.throneRoom.rare;break;
            case 4:a = unsafeWindow.g_js_strings.throneRoom.epic;break;
            case 5:a = unsafeWindow.g_js_strings.throneRoom.wondrous;break;
            default:a = unsafeWindow.g_js_strings.throneRoom.simple;break;
        }
        switch (qualityto) {
            case 0:b = unsafeWindow.g_js_strings.throneRoom.simple;break;
            case 1:b = unsafeWindow.g_js_strings.throneRoom.common;break;
            case 2:b = unsafeWindow.g_js_strings.throneRoom.uncommon;break;
            case 3:b = unsafeWindow.g_js_strings.throneRoom.rare;break;
            case 4:b = unsafeWindow.g_js_strings.throneRoom.epic;break;
            case 5:b = unsafeWindow.g_js_strings.throneRoom.wondrous;break;
            default:b = unsafeWindow.g_js_strings.throneRoom.simple;break;
        }
        if (document.getElementById('ShowQueue')) {
            var row = ById('ShowQueue').insertRow(0);
            row.vAlign = 'top';
            row.style.color = "black";
            if (active) row.style.color = "green";
            row.insertCell(0).innerHTML = id+1;
            row.insertCell(1).innerHTML = name;
            if (action == ""+culang.throneStuffEnhance+"") {
                row.insertCell(2).innerHTML = a + " -> " + b;
                row.insertCell(3).innerHTML = levelfrom;
            }
            if (action == ""+culang.throneStuffUpgrade+"") {
                row.insertCell(2).innerHTML = a;
                row.insertCell(3).innerHTML = levelfrom + " -> " + levelto;
            }
            row.insertCell(4).innerHTML = action;
            row.insertCell(5).innerHTML = cost;
            row.insertCell(6).innerHTML = '<a id="queueDelete_' + id + '"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></span></a>';
            ById('queueDelete_' + id).addEventListener('click', function(){
                // if (ThroneOptions.Items[id].active ==true) ThroneOptions.Tries=0;
            if (ThroneOptions.Items.length ==0 && ThroneOptions.Active && ById('ShowStatus')) {
               document.getElementById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoItems+"</i>";
             }
            if (!ThroneOptions.Active && ById('ShowStatus')) document.getElementById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
            ThroneOptions.Items.splice (id,1);
                saveThroneOptions();
                t.checkUpgradeInfo(false);
                t.PaintQueue();
                if (ThroneOptions.Items.length>0) t.paintInfo();
                else ById('ShowInfo').innerHTML = "";
            }, false);

        }
    },

    _addTabHeader: function() {
        var t = Tabs.ThroneStuff;
        if (ById('ShowQueue')) {
            var row = ById('ShowQueue').insertRow(0);
            row.vAlign = 'top';
            row.style.color = "black";
            row.insertCell(0).innerHTML = "<b><u>"+culang.throneStuffId+"</u></b>";
            row.insertCell(1).innerHTML = "<b><u>"+culang.mainName+"</u></b>";
            row.insertCell(2).innerHTML = "<b><u>"+culang.throneQuality+"</u></b>";
            row.insertCell(3).innerHTML = "<b><u>"+culang.throneLevel+"</u></b>";
            row.insertCell(4).innerHTML = "<b><u>"+culang.throneAction+"</u></b>";
            row.insertCell(5).innerHTML = "<b><u>"+culang.throneStuffCost+"</u></b>";
            row.insertCell(6).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
        }
    },

    PaintHistory : function() {
        var t = Tabs.ThroneStuff;
        var popHistory = null;
        popHistory = new CPopup('pbShowHistory', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=2 cellspacing=2 width=100% class="pbShowBarbs" id="pbBars1">';
        popHistory.getMainDiv().innerHTML = '</table></div>' + m;
        popHistory.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.throneStuffUpgradeEnhanceList+'</div>';
        for (i=0;i<t.log.length;i++){
            var row = ById('pbBars1').insertRow(0);
            row.vAlign = 'top';
            row.style.color = "black";
            row.insertCell(0).innerHTML = t.log[i].time;
            row.insertCell(1).innerHTML = t.log[i].name;
            row.insertCell(2).innerHTML = t.log[i].action;
            row.insertCell(3).innerHTML = t.log[i].tries;
            row.insertCell(4).innerHTML = t.log[i].good;
            row.insertCell(5).innerHTML = t.log[i].bad;
        }
        var row = ById('pbBars1').insertRow(0);
        row.vAlign = 'top';
        row.style.color = "black";
        row.insertCell(0).innerHTML = "<b><u>"+culang.mainTime+"</u></b>";
        row.insertCell(1).innerHTML = "<b><u>"+culang.mainName+"</u></b>";
        row.insertCell(2).innerHTML = "<b><u>"+culang.throneAction+"</u></b>";
        row.insertCell(3).innerHTML = "<b><u>"+culang.throneStuffTries+"</u></b>";
        row.insertCell(4).innerHTML = "<b><u>"+culang.throneStuffGoodReq+"</u></b>";
        row.insertCell(5).innerHTML = "<b><u>"+culang.throneStuffBadReq+"</u></b>";
        popHistory.show(true)    ;
    },

    PaintSalvageHistory : function() {
        var t = Tabs.ThroneStuff;
        try {
        var popHistory = null;
        popHistory = new CPopup('pbSalvageShowHistory', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto"><TABLE align=center cellpadding=2 cellspacing=2 width=100% class="pbShowBarbs" id="pbBars2">';
        popHistory.getMainDiv().innerHTML = '</table></div>' + m;
        popHistory.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.throneStuffSalvageList+'</div>';
        for (i=0;i<t.SalvageLog.length;i++){
            var row = ById('pbBars2').insertRow(0);
            row.vAlign = 'top';
            row.style.color = "black";
            row.insertCell(0).innerHTML = t.SalvageLog[i].time;
            row.insertCell(1).innerHTML = t.SalvageLog[i].stones;
            row.insertCell(2).innerHTML = t.SalvageLog[i].msg;
        }
        var row = ById('pbBars2').insertRow(0);
        row.vAlign = 'top';
        row.style.color = "black";
        row.insertCell(0).innerHTML = "<b><u>"+culang.mainTime+"</u></b>";
        row.insertCell(1).innerHTML = "<img height=18 src='"+IMGastone30+"' title='"+uW.g_js_strings.commonstr.aetherstone+"'>";
        row.insertCell(2).innerHTML = "<b><u>"+culang.throneAction+"</u></b>";
        popHistory.show(true)    ;
        } catch(ex) {
            alert(inspect(ex,5));
        }
    },

    PaintSalvagePreview : function() {
        var t = Tabs.ThroneStuff;
        var popPreview = null;
        popPreview = new CPopup('pbSalvageShowPreview', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:460px; height:460px; overflow-y:auto">';
        m+='<div>'+culang.mainShow+': <input type="checkbox" id="SalvagePreviewShowDel" '+(ThroneOptions.SalvageV2.Preview.ShowDel?'checked':'')+' /> '+culang.throneStuffSalvagePreviewDeleteKeep+' <input type="checkbox" id="SalvagePreviewShowKeep" '+(ThroneOptions.SalvageV2.Preview.ShowKeep?'checked':'')+' /> '+culang.throneStuffSalvagePreviewDeleteKeep2+'</div>'
        m+='<div>'+culang.throneStuffSalvagePreviewDeleteKeepNote+'</div>'
        m+='<TABLE align=center cellpadding=2 cellspacing=2 width=100% class="pbShowBarbs" id="pbBars3"></table>';
        m+='</div>';
        popPreview.getMainDiv().innerHTML = m;
        ById("SalvagePreviewShowDel").addEventListener ('change', function(){
            var t = Tabs.ThroneStuff;
            ThroneOptions.SalvageV2.Preview.ShowDel = ById("SalvagePreviewShowDel").checked;
            saveThroneOptions();
            t.PaintSalvagePreview();
        },false);
        ById("SalvagePreviewShowKeep").addEventListener ('change', function(){
            var t = Tabs.ThroneStuff;
            ThroneOptions.SalvageV2.Preview.ShowKeep = ById("SalvagePreviewShowKeep").checked;
            saveThroneOptions();
            t.PaintSalvagePreview();
        },false);

        popPreview.getTopDiv().innerHTML = '<DIV class="popupBanner">'+""+culang.throneStuffSalvagePreviewHead+""+'</div>';
        for (i=t.SalvagePreviewList.length-1;i>=0;i--){
            if(!((ThroneOptions.SalvageV2.Preview.ShowDel && t.SalvagePreviewList[i].del) ||
                (ThroneOptions.SalvageV2.Preview.ShowKeep && !t.SalvagePreviewList[i].del))) continue;
            var row = ById('pbBars3').insertRow(0);
            row.vAlign = 'top';
            row.style.color = "black";
            row.insertCell(0).innerHTML = t.SalvagePreviewList[i].number+(t.SalvagePreviewList[i].del?"":"* ")+(t.SalvagePreviewList[i].isInFreeRow?'':' !'); ;
            row.insertCell(1).innerHTML = "";//t.SalvagePreviewList[i].stones;
            row.insertCell(2).innerHTML = t.SalvagePreviewList[i].msg;
            row.insertCell(3).innerHTML = t.SalvagePreviewList[i].keepReason;
        }
        var row = ById('pbBars3').insertRow(0);
        row.vAlign = 'top';
        row.style.color = "black";
        row.insertCell(0).innerHTML = "#";
        row.insertCell(1).innerHTML = "<img height=18 src='"+IMGastone30+"' title='"+uW.g_js_strings.commonstr.aetherstone+"'>";
        row.insertCell(2).innerHTML = "<b><u>"+culang.throneHeadItemList+"</u></b>";
        row.insertCell(3).innerHTML = "?";
        popPreview.show(true);
    },
    
    addToQueue : function (id,action){
        var t= Tabs.ThroneStuff;
        if (ById('ShowHoover')) ById('ShowHoover').innerHTML = "";
        ThroneOptions.Items.push ({
            id:id,
            action:action,
            name:getThroneItemName(id),
            qualityfrom:0,
            qualityto:0,
            levelfrom:0,
            levelto:0,
            cost:0,
            active:false
        });
        saveThroneOptions();
        t.checkUpgradeInfo(false);

        if (ThroneOptions.Active && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNextItem+"</i>"
        if (!ThroneOptions.Active && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
    },

    checkUpgradeInfo : function (firstRun){
        var t= Tabs.ThroneStuff;
        var countUpgrade = 0;
        var countEnhance = 0;
        var levelfrom = 0;
        var levelto =0;
        var qualityfrom = 0;
        var qualityto = 0;
        if (ThroneOptions.Items.length == 0) return;
        for (k=0;k<ThroneOptions.Items.length;k++){
            countUpgrade = 0;
            countEnhance = 0;
            if (unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]] != undefined) {
                if (k>0) for (l=0;l<k;l++) {
                    if (ThroneOptions.Items[l]["id"] == ThroneOptions.Items[k]["id"] && ThroneOptions.Items[l]["action"] == ""+culang.throneStuffUpgrade+"") {countUpgrade++;}
                    if (ThroneOptions.Items[l]["id"] == ThroneOptions.Items[k]["id"] && ThroneOptions.Items[l]["action"] == ""+culang.throneStuffEnhance+"") {countEnhance++;}
                }
                if (ThroneOptions.Items[k]["action"] == ""+culang.throneStuffUpgrade+"") {
                    ThroneOptions.Items[k]["levelfrom"] = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]["level"]) + countUpgrade;
                    ThroneOptions.Items[k]["levelto"] = parseInt(ThroneOptions.Items[k]["levelfrom"]) +1;
                    ThroneOptions.Items[k]["qualityfrom"] = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]["quality"]) + countEnhance;
                    if (ThroneOptions.Items[k]["levelto"]>12 && !firstRun) {alert(""+culang.throneStuffEUQueueUpgradeLevel12+"");ThroneOptions.Items.splice (k,1);saveThroneOptions();return;}
                }
                if (ThroneOptions.Items[k]["action"] == ""+culang.throneStuffEnhance+"") {
                    ThroneOptions.Items[k]["qualityfrom"] = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]["quality"]) + countEnhance;
                    ThroneOptions.Items[k]["qualityto"] = parseInt(ThroneOptions.Items[k]["qualityfrom"]) +1;
                    ThroneOptions.Items[k]["levelfrom"] = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]["level"]) + countUpgrade;
                    if (ThroneOptions.Items[k]["qualityto"]>5 && !firstRun) {
                        alert(""+culang.throneStuffEUQueueUpgradeQuality5+"");
                        ThroneOptions.Items.splice (k,1);
                        t.PaintQueue();
                        t.paintInfo();
                        saveThroneOptions();
                        return;
                    }
                }
                if (ThroneOptions.Items[k]["action"] == ""+culang.throneStuffEnhance+"") var lvl = parseInt(ThroneOptions.Items[k]["qualityfrom"]) +1;
                if (ThroneOptions.Items[k]["action"] == ""+culang.throneStuffUpgrade+"") var lvl = parseInt(ThroneOptions.Items[k]["levelfrom"]) +1;
                costAction = ThroneOptions.Items[k]["action"].toLowerCase();
                if (unsafeWindow.cm.thronestats[costAction][lvl] != undefined) ThroneOptions.Items[k]["cost"] = unsafeWindow.cm.thronestats[costAction][lvl].Stones;
                else ThroneOptions.Items.splice (k,1);
            } else ThroneOptions.Items.splice (k,1);
        }
        t.paintHoover();
        t.PaintQueue();
        t.paintInfo();
        saveThroneOptions();
    },

    PaintQueue : function (){
        var t= Tabs.ThroneStuff;
        if (ById('ShowQueueDiv')) ById('ShowQueueDiv').innerHTML = '<TABLE id=ShowQueue class=pbStat align="center" width=90%></table>';
        for (k=(ThroneOptions.Items.length-1);k>=0;k--){
            if (typeof(unsafeWindow.kocThroneItems[ThroneOptions.Items[k]["id"]]) == 'object') t._addTab(k,ThroneOptions.Items[k]["name"],ThroneOptions.Items[k]["qualityfrom"],ThroneOptions.Items[k]["qualityto"],ThroneOptions.Items[k]["levelfrom"],ThroneOptions.Items[k]["levelto"],ThroneOptions.Items[k]["action"],ThroneOptions.Items[k]["active"],ThroneOptions.Items[k]["cost"]);
            else ThroneOptions.Items.splice (k,1);
        }
        t._addTabHeader();
    },

    doAction : function (){
        var t= Tabs.ThroneStuff;
        var now = new Date().getTime()/1000.0;
        if (!ThroneOptions.Active) return;
        if (ThroneOptions.Items.length ==0) {
            if ( ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoItems+"</i>"
            return;
        }
        ThroneOptions.Items["0"]["active"] = true;
        t.PaintQueue();
        if (unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken == true && Seed.queue_throne.end == undefined){
            unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken = false;
            unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].brokenType = "";
            setTimeout(t.doRepair,5000);
            clearTimeout(t.setActionTimer);
            t.setActionTimer = setInterval(t.doAction,10000);
            return;
        }
        if (unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].isBroken == false && Seed.queue_throne.end == undefined){
            if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDo+" " + ThroneOptions.Items["0"]["action"] + " "+culang.throneStuffEUQueueDo2+"</i>";
            if (ThroneOptions.Items["0"]["action"] == ""+culang.throneStuffUpgrade+"") setTimeout(t.doUpgrade,5000);
            if (ThroneOptions.Items["0"]["action"] == ""+culang.throneStuffEnhance+"") setTimeout(t.doEnhance,5000);
            clearTimeout(t.setActionTimer);
            t.setActionTimer = setInterval(t.doAction,10000);
        }
    },

    doEnhance : function() {
        var t = Tabs.ThroneStuff;
        if (typeof(unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'object') {
            var item = unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]];
        } else return;
        var cityid = 0;
        if (ThroneOptions.CityMax) {
            var max = 0;
            for (var k in Cities.byID) {
                if (parseInt(Seed.resources["city"+k]["rec5"][0]) > max) {
                    max = parseInt(Seed.resources["city"+k]["rec5"][0]);
                    if (parseInt(Seed.resources["city"+k]["rec5"][0]) > parseInt(ThroneOptions.Items["0"]["cost"])) {
                        cityid = k;
                    }
                }
            }
            
        } else {
            for (var k in Cities.byID) {
                if (parseInt(Seed.resources["city"+k]["rec5"][0]) > parseInt(ThroneOptions.Items["0"]["cost"]))    {
                    cityid = k;
                    break;
                }
            }
        }
        if(cityid == 0){
            if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoAetherstone+" "+ parseInt(Seed.resources["city"+k]["rec5"][0])+"</i>";
            // actionLog(""+culang.tabLabelThrone+"",""+culang.throneStuffEUQueueNoAetherstoneLog+" " + parseInt(Seed.resources["city"+k]["rec5"][0]) + " - "+culang.throneQualityUpgradeNote+" " + parseInt(ThroneOptions.Items["0"]["cost"])+" "+culang.throneQualityUpgradeNote2+"" );
            return;
        }
        var buffItemId = 0;
        if (ThroneOptions.i20004 && Seed.items.i20004 && parseInt(Seed.items.i20004) > 0) buffItemId = 20004;
        if (ThroneOptions.i20002 && Seed.items.i20002 && parseInt(Seed.items.i20002) > 0) buffItemId = 20002;
        if (ThroneOptions.i20001 && Seed.items.i20001 && parseInt(Seed.items.i20001) > 0) buffItemId = 20001;
        if(buffItemId > 0){
            if (ById('ShowStatus')) ById('ShowStatus').innerHTML = culang.throneStuffItemUse+" <b>"+uW.itemlist['i'+buffItemId].name+"</b><br>";
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'upgradeQuality';
        params.throneRoomItemId = ThroneOptions.Items["0"]["id"];
        params.buffItemId = buffItemId;
        params.payment = "aetherstone";
        params.cityId = cityid;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                var t = Tabs.ThroneStuff;
                if(rslt.ok){
                    if (buffItemId > 0) {
                        Seed.items['i'+buffItemId] = Seed.items['i'+buffItemId] - 1;
                        if (Seed.items['i'+buffItemId] < 0) Seed.items['i'+buffItemId] = 0;
                        uW.ksoItems[buffItemId].subtract();
                    }
                    if (rslt.gems > 0)
                    {
                        if (ById('ShowStatus')) ById('ShowStatus').innerHTML = ById('ShowStatus').innerHTML +'<i>'+culang.throneStuffSpendGems+'</i>';
                        ThroneOptions.Active = false;
                        saveThroneData();
                    }
                    Seed.resources["city" + cityid]["rec5"][0] -= rslt.aetherstones;
                    item.level = rslt.item.level;
                    item.quality = rslt.item.quality
                    item.status = rslt.item.status;
                    if (rslt.success){
                        item.name = item.createName(); // ???
                        ThroneOptions.Good++;
                        ThroneOptions.Tries++;
                        t.addToLog(ThroneOptions.Items["0"]["id"],ThroneOptions.Items["0"]["action"],ThroneOptions.Tries,ThroneOptions.Good,ThroneOptions.Bad);
                        ThroneOptions.Tries = 0;
                        ThroneOptions.Good = 0;
                        ThroneOptions.Bad = 0;
                        ThroneOptions.Items.splice (0,1);
                        saveThroneOptions();
                        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                        params.emailTo = Seed.player['name'];
                        params.subject = ''+culang.throneStuffERessourceMailSubject+' '+ getThroneItemName(item.id);
                        var effft="",x=0,s = item;
                        for (var u in s.effects) {
                            L = s.effects[u];
                            effect = uW.cm.thronestats.effects[L.id];
                            tier = uW.cm.thronestats.tiers[L.id][L.tier];
                            var percent = + tier.base + (s.level * s.level + s.level) * + tier.growth * 0.5;
                            percent = percent > 0 ? "+" + percent : + percent;
                            percent = Math.ceil(percent);
                            effft += percent + "% " + effect[1] + " %0A";
                        }
                        params.message = effft;
                        params.requestType = "COMPOSED_MAIL";;
                        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {method: "post",parameters: params,onSuccess: function (rslt) {

                        },onFailure: function () {},});
                        if (ById('ShowTries')) ById('ShowTries').innerHTML = ""+culang.throneStuffEUQueueShowTriesNone+"";
                    }else{
                        if (rslt['break']) {
                            item.isBroken = true;
                            item.brokenType = "quality";
                        }
                        item.quality = rslt.item.quality;
                        item.level = rslt.item.level;
                        item.status = rslt.item.status;
                        item.name = item.createName(); 
                        ThroneOptions.Tries++;
                        ThroneOptions.Good++;
                        if (ById('ShowStatus')) ById('ShowStatus').innerHTML = ById('ShowStatus').innerHTML +culang.throneStuffERStatusFaild+' <br /><span class="boldRed">'+culang.throneStuffERStatusFaild2+'</span> <u>' + unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]].name +"</u><br /><i>"+culang.throneStuffERStatusFaild3+"</i>";
                        if (ById('ShowTries')) ById('ShowTries').innerHTML = "<b>"+culang.throneStuffEUQueueShowTries+"</b> " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;
                    }
                    uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
                    t.checkUpgradeInfo(false);
                    t.PaintQueue();
                    saveThroneOptions();
                } else {
                    // actionLog(""+culang.tabLabelThrone+"",""+culang.throneStuffRequestError+" "+ThroneOptions.Items["0"]["id"]+": " + transport.responseText);
                    if(rslt.error_code==256) {

                        /* setTimeout(function() {
                         reloadKOC();
                         },2000);

                         */
                        item.isBroken = true;
                        item.brokenType = "quality";
                        item.name = item.createName(); // ???
                        uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
                        ThroneOptions.Tries++;
                        saveThroneOptions();
                        t.doRepair();

                        return;
                    }
                    ThroneOptions.Bad++;
                    saveThroneOptions();
                }
                return;
            },
            onFailure: function () {
                return;
            },
        });
    },

    doUpgrade : function() {
        var t = Tabs.ThroneStuff;
        if (typeof(uW.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'object') {
            var item = uW.kocThroneItems[ThroneOptions.Items["0"]["id"]];
        } else return;
        var cityid = 0;
        if (ThroneOptions.CityMax) {
            var max = 0;
            for (var k in Cities.byID) {
                if (parseInt(Seed.resources["city"+k]["rec5"][0]) > max) {
                    max = parseInt(Seed.resources["city"+k]["rec5"][0]);
                    if (parseInt(Seed.resources["city"+k]["rec5"][0]) > parseInt(ThroneOptions.Items["0"]["cost"])) {
                        cityid = k;
                    }
                }
            }
            
        } else {
            for (var k in Cities.byID) {
                if (parseInt(Seed.resources["city"+k]["rec5"][0]) > parseInt(ThroneOptions.Items["0"]["cost"]))    {
                    cityid = k;
                    break;
                }
            }
        }
        if(cityid == 0){
            if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoAetherstone+"</i>";
            return;
        }
        var buffItemId = 0;
        if (ThroneOptions.i20006 && Seed.items.i20006 && parseInt(Seed.items.i20006) > 0) buffItemId = 20006;
        if (ThroneOptions.i20005 && Seed.items.i20005 && parseInt(Seed.items.i20005) > 0) buffItemId = 20005;
        if (ThroneOptions.i20002 && Seed.items.i20002 && parseInt(Seed.items.i20002) > 0) buffItemId = 20002;
        if (ThroneOptions.i20001 && Seed.items.i20001 && parseInt(Seed.items.i20001) > 0) buffItemId = 20001;
        if(buffItemId > 0){
            if (ById('ShowStatus')) ById('ShowStatus').innerHTML = culang.throneStuffItemUse+" <b>"+uW.itemlist['i'+buffItemId].name+"</b><br>";
        }
        var params = uW.Object.clone(uW.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'upgradeLevel';
        params.throneRoomItemId = ThroneOptions.Items["0"]["id"];
        params.buffItemId = buffItemId;
        params.payment = "aetherstone";
        params.cityId = cityid;
        new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                    if (buffItemId > 0) {
                        Seed.items['i'+buffItemId] = parseInt(Seed.items['i'+buffItemId]) - 1;
                        if (Seed.items['i'+buffItemId] < 0) Seed.items['i'+buffItemId] = 0;
                        uW.ksoItems[buffItemId].subtract();
                    }
                    if (rslt.gems > 0)
                    {
                        if (ById('ShowStatus')) ById('ShowStatus').innerHTML = ById('ShowStatus').innerHTML +'<i>'+culang.throneStuffSpendGems+'</i>';
                        ThroneOptions.Active = false;
                        saveThroneData();
                    }
                    Seed.resources["city" +cityid]["rec5"][0] -= rslt.aetherstones;
                    if (rslt.success)
                    {
                        item.level = rslt.item.level;
                        ThroneOptions.Tries++;
                      ThroneOptions.Good++;
                        item.quality = rslt.item.quality;
                        item.name = item.createName(); // ???
                        t.addToLog(ThroneOptions.Items["0"]["id"],ThroneOptions.Items["0"]["action"],ThroneOptions.Tries,ThroneOptions.Good,ThroneOptions.Bad);
                        ThroneOptions.Tries = 0;
                        ThroneOptions.Good = 0;
                        ThroneOptions.Bad = 0;
                        saveThroneOptions();

                        ThroneOptions.Items.splice (0,1);
                        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                        params.emailTo = Seed.player['name'];
                        params.subject = ''+culang.throneStuffURessourceMailSubject+' '+ getThroneItemName(item.id);
                        var effft="";
                        var x=0;
                        s = item;
                        for (var u in s.effects) {
                            L = s.effects[u];
                            effect = uW.cm.thronestats.effects[L.id];
                            tier = uW.cm.thronestats.tiers[L.id][L.tier];
                            var percent = + tier.base + (s.level * s.level + s.level) * + tier.growth * 0.5;
                            percent = percent > 0 ? "+" + percent : + percent;
                            percent = Math.ceil(percent);

                            effft += percent + "% " + effect[1] + " %0A";

                        }
                        params.message = effft;
                        params.requestType = "COMPOSED_MAIL";;
                        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
                            method: "post",
                            parameters: params,
                            onSuccess: function (rslt) {

                            },
                            onFailure: function () {

                            },
                        });
                        if (ById('ShowTries'))ById('ShowTries').innerHTML = ""+culang.throneStuffEUQueueShowTriesNone+"";
                    }
                    else
                    {
                        if (rslt['break']) {
                            item.isBroken = true;
                            item.brokenType = "level";
                        }
                        item.quality = rslt.item.quality;
                        item.level = rslt.item.level;
                        item.status = rslt.item.status;
                        item.name = item.createName(); 
                        ThroneOptions.Tries++;
                        ThroneOptions.Good++;
                        saveThroneOptions();
                        if (ById('ShowStatus')) ById('ShowStatus').innerHTML = ById('ShowStatus').innerHTML +'<span class="boldRed">'+culang.throneStuffURStatusFaild+'</span><br />'+culang.throneStuffERStatusFaild2+' <u>' + getThroneItemName(ThroneOptions.Items["0"]["id"]) +"</u><br /><i>"+culang.throneStuffERStatusFaild3+"</i>";
                        if (ById('ShowTries')) ById('ShowTries').innerHTML = "<b>"+culang.throneStuffEUQueueShowTries+"</b> " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;
                    }
                    unsafeWindow.cm.ThroneView.renderInventory(unsafeWindow.kocThroneItems);

                    t.checkUpgradeInfo(false);
                    t.PaintQueue();
                    saveThroneOptions();
                } else {
                    ThroneOptions.Bad++;
                    saveThroneOptions();
                }
                return;
            },
            onFailure: function () {
                return;
            },
        });
    },

    doRepair : function() {
        var t = Tabs.ThroneStuff;
        var params = uW.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'timeRepair';
        params.throneRoomItemId = ThroneOptions.Items["0"]["id"];        
    new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                    if(rslt.ok){
                              ThroneOptions.RepairEnd = rslt.eta; 
                              var now = new Date().getTime()/1000.0;
                              var t = Tabs.ThroneStuff;
                              t.setRepairTimer = setInterval (t.repairTimerUpdate,1000); 
                      Seed.queue_throne.itemId= ThroneOptions.Items["0"]["id"];
                             Seed.queue_throne.start=unixTime();
                     Seed.queue_throne.end= rslt.eta;
                     t.repairId = ThroneOptions.Items["0"]["id"];
                     t.repairEnd = rslt.eta;
                     uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
                     var x = rslt.eta - unixTime();
                    //ThroneOptions.Good++;
                    saveThroneOptions();
                   } else {    
                           //ThroneOptions.Good++;
                        saveThroneOptions();
                   }        
                   return;
            },
            onFailure: function () {
               return;
            },
        });
    },

    doEquip : function(n,preset) {
        var t = Tabs.ThroneStuff;
        if (typeof(unsafeWindow.kocThroneItems[n]) == 'object') {
            var y = unsafeWindow.kocThroneItems[n];
        } else return;

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        //logit(n.toSource());
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'equipItem';
        params.itemId = y.id;
        params.presetId = ById("preset").value;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                    unsafeWindow.cm.ThroneView.clickItemEquip(y);
                    t.FillEquipCheckboxes();
                }
            },
            onFailure: function () {
                return;
            },
        });
    },

    doUnequip : function(n,preset) {
        var t = Tabs.ThroneStuff;
        if (typeof(unsafeWindow.kocThroneItems[n]) == 'object') {
            var y = unsafeWindow.kocThroneItems[n];
        } else return;

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        //logit(n.toSource());
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'unequipItem';
        params.itemId = y.id;
        params.presetId = ById("preset").value;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                    unsafeWindow.cm.ThroneView.clickItemUnequip(y);
                    t.FillEquipCheckboxes();
                }
            },
            onFailure: function () {
                return;
            },
        });
    },

    repairTimerUpdate :function (){
        var t = Tabs.ThroneStuff;
        if (ThroneOptions.Items.length == 0) return;
        var now = new Date().getTime()/1000.0;
        var diff = 0;
        if (Seed.queue_throne.end == undefined) return;
        else diff = Seed.queue_throne.end - now;
        if (diff <0){
            clearTimeout(t.setRepairTimer);
            if (ThroneOptions.Active && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueWaiting+"</i>";
            if (!ThroneOptions.Active && ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueDisabled+"</i>";
            unsafeWindow.kocThroneItems[Seed.queue_throne.itemId].isBroken = false;
            Seed.queue_throne = "";
            return;
        } else {
            if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<b>"+culang.throneStuffRepairItem+"</b> " + getThroneItemName(ThroneOptions.Items["0"]["id"]) + "<br/><b>"+culang.throneStuffRepairTimeLeft+"</b> <span class='boldRed'>" + timestr(diff)+ " <sup>("+ timestr(Seed.queue_throne.end - Seed.queue_throne.start) + ")</sup></span>";
            if (ById('ShowTries')) ById('ShowTries').innerHTML = "<b>"+culang.throneStuffEUQueueShowTries+"</b> " + ThroneOptions.Tries + "<br />"+culang.throneStuffEUQueueShowTriesGood+" " + ThroneOptions.Good + "  - "+culang.throneStuffEUQueueShowTriesBad+" " + ThroneOptions.Bad;
        }

    },

    paintInfo : function (){
        var t = Tabs.ThroneStuff;
        if (ThroneOptions.Items["0"]==undefined) ThroneOptions.Items=[];
        if (typeof(unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]) == 'number') {
            var y = unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]];
        } else return;
        var id =0;
        var tier=0;
        var Current=0;
        var Next=0;
        m="<TABLE width=80% height=0% align='center' class=pdxTab><TR><TD><B>"+culang.throneStuffItemCurrent+"</b></td><TD><B>"+culang.throneStuffItemNext+"</b></td>";
        for (i=1;i<=5;i++) {
            id = y["effects"]["slot"+i]["id"];
            tier = parseInt(y["effects"]["slot"+i]["tier"]);
            level = y["level"];
            p = unsafeWindow.cm.thronestats.tiers[id][tier];
            Current = p.base + ((level * level + level) * p.growth * 0.5);
            level++;
            Next = p.base + ((level * level + level) * p.growth * 0.5);;
            var quality = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]["quality"]);
            if (ThroneOptions.Items["0"]["action"] == ""+culang.throneStuffEnhance+"") {
                if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td>';
                else m+='<TR><TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td>';
                if (i<=(quality+1)) m+='<TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
                else m+='<TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
            }
            if (ThroneOptions.Items["0"]["action"] == ""+culang.throneStuffUpgrade+"") {
                if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td>';
                else m+='<TR><TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td>';
                if (i<=quality) m+='<TD><FONT color=green>' + Next + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
                else m+='<TD><FONT color=red>' + Next + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
            }
        }
        m+="</table>"
        document.getElementById('ShowInfo').innerHTML = m;

    },

    paintHoover : function (){
        var t = Tabs.ThroneStuff;
        if (!ById('ThroneItems')) return;
        var z = ById('ThroneItems').value;
        var y = unsafeWindow.kocThroneItems[z];
        var id =0;
        var tier=0;
        var Current=0;
        //var imagesrc='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/'+faction+'/'+faction+'_'+type+'_normal_1.png'; 
        var imagesrc='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/throne/icons/30/'+y.faction+'/'+y.faction+'_'+y.type+'_normal_1_'+y.quality+'.png'; 
        m="<TABLE width=80% height=0% align='center' class=pdxTab><TR>";
        m+="<TD><TABLE class=pdxTab>";
        m+="<TR><TD><img src='"+imagesrc+"' height=30 width=30 /></td></tr>";
        m+="</TABLE>";
        m+="<td><TABLE>";
        for (i=1;i<=5;i++) {
            id = y["effects"]["slot"+i]["id"];
            tier = parseInt(y["effects"]["slot"+i]["tier"]);
            level = y["level"];
            p = unsafeWindow.cm.thronestats.tiers[id][tier];
            Current = p.base + ((level * level + level) * p.growth * 0.5);

            //if (ThroneOptions.Items["0"])
            // var quality = parseInt(unsafeWindow.kocThroneItems[ThroneOptions.Items["0"]["id"]]["quality"]);
            //else
            var quality = y.quality
            if (i<=quality) m+='<TR><TD><FONT color=green>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
            else m+='<TR><TD><FONT color=red>' + Current + "% " + unsafeWindow.cm.thronestats["effects"][id]["1"] + '</font></td></tr>';
        }
        m+="</table></td></tr></table>"
        ById('ShowHoover').innerHTML = m;

    },

    paintStones : function (){
        var t = Tabs.ThroneStuff;
        m="<TABLE width=90% height=0% class=pdxTab><TR><TD><img height=18 src='"+IMGastone30+"'></td>";
        for (i=0;i<Seed.cities.length;i++) m+='<TD>' + Seed.cities[i]["1"] + '</td>';
        m+="</tr><TR><TD></td>"
        for (i=0;i<Seed.cities.length;i++) m+='<TD>' + addCommas(Seed.resources["city"+Seed.cities[i]["0"]]["rec5"][0]) + '</td>';
        m+="</tr></table>"
        if (ById('ShowStones')) ById('ShowStones').innerHTML = m;
    },

    addToLog : function (id,action,tries,good,bad){
        var t = Tabs.ThroneStuff;
        var now = new Date();
        var time = now.getDate() +"/"+ (now.getMonth()+1) +"/"+ now.getFullYear() +"  "+ now.getUTCHours() + ":" + now.getMinutes();
        var name = getThroneItemName(id);
        t.log.push ({time:time,name:name,action:action,tries:tries,good:good,bad:bad});
        if (t.log.length > 50) t.log.splice(0,1);
        GM_setValue ('ThroneHistory_'+getServerId(), JSON2.stringify(t.log));
    },


    addToSalvageLog : function (msg,stones){
        var t = Tabs.ThroneStuff;
        var now = new Date();
        D = t.format00(now.getDate());
        M = t.format00(now.getMonth()+1);
        Y = t.format00(now.getFullYear());
        h = t.format00(now.getHours());
        m = t.format00(now.getMinutes());
        var time =  D +"/"+ M +"/"+ Y +"  "+ h + ":" + m;
        t.SalvageLog.push ({time:time,stones:stones,msg:msg});
        if (t.SalvageLog.length > 100) t.SalvageLog.splice(0,1);
        GM_setValue ('ThroneSalvageHistory_'+getServerId(), JSON2.stringify(t.SalvageLog));
    },

    addToSalvagePreviewList : function (number,msg,stones,isInFreeRow,del,keepReason){
        var t = Tabs.ThroneStuff;
        t.SalvagePreviewList.push ({number:number,isInFreeRow:isInFreeRow,stones:stones,msg:msg,del:del,keepReason:keepReason});
    },

    format00 : function (number) { if (number<10) number="0" + number; return number;},

    salvageCheck : function (){
        var t = Tabs.ThroneStuff;

        freeRowItems=(5*Seed.throne.rowNum);
        if(false) GM_log("salvageCheck()"
            +"\n\t"+"freeRows:"+Seed.throne.rowNum
            +"\n\t"+"freeRowItems:"+freeRowItems
        );

        var del = true;
        var keepReason="";
        var level = false;
        var type ="";
        var upgrading = false;
        var count=0;
        var salvageMsgs="";
        var effectIndex3;
        var effectIndex4; 
        var effectIndex5; 
        var countEffect;
        if(t.SalvagePreviewMode){
            t.SalvagePreviewList=[];
        } else {
            if(!Options.ThroneDeleteItems) { clearTimeout(t.timersalvage);return; }
            if (t.SalvageRunning == true) return; t.SalvageRunning = true;
        }

        for (m in unsafeWindow.kocThroneItems) {
            var item = unsafeWindow.kocThroneItems[m];
            // GM_log("item.id: "+item.id);
            if (typeof(item.id) != 'number') continue;
            count++;
            isInFreeRow = (count <= (parseInt(Seed.throne.rowNum) * 5));
            if (!(isInFreeRow || t.SalvagePreviewMode)) continue;

            del = true;
            keepReason = "";

            if (item.isEquipped || item.level > 0 || item.isBroken || item.id == t.LastDeleted) {
                del = false;
                keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonELB + "";
            }
            if (del) { // save first X items Filter
                if (count <= ThroneOptions.SalvageV2.SaveXitems) {
                    del = false;
                    keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonSaveFirst + " " + ThroneOptions.SalvageV2.SaveXitems + " " + culang.throneStuffSalvagePreviewKeepReasonSaveFirst2 + "";
                }
            }
            if (del) { // Upgrading Filter
                upgrading = false;
                for (k in ThroneOptions.Items) {
                    if (ThroneOptions.Items[k]["id"] == item.id) upgrading = true;
                }
                if (upgrading) {
                    del = false;
                    keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonItemScheduled + "";
                }
            }
            if (del) { // Quality Filter
                if (ThroneOptions.SalvageV2.QualityFilter == 0) {
                }
                else if (item.quality >= ThroneOptions.SalvageV2.QualityFilter) {
                    del = false;
                    keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonQualityReached + "";
                }
            }
            if (del) { // Type Filter
                if (
                    (item.type == "advisor"             && ThroneOptions.SalvageV2.TypeFilter.Advisor) ||
                    (item.type == "banner"              && ThroneOptions.SalvageV2.TypeFilter.Banner ) ||
                    (item.type == "chair"               && ThroneOptions.SalvageV2.TypeFilter.Chair  ) ||
                    (item.type == "table"               && ThroneOptions.SalvageV2.TypeFilter.Table  ) ||
                    (item.type == "window"              && ThroneOptions.SalvageV2.TypeFilter.Window ) ||
                    (item.type == "trophy"              && ThroneOptions.SalvageV2.TypeFilter.Trophy ) ||
                    (item.type == "candelabrum"      && ThroneOptions.SalvageV2.TypeFilter.Candelabrum )
                    ) {
                    del = false;
                    keepReason = "" + culang.throneStuffSalvagePreviewKeepReasonTypeMatching + " (" + item.type + ")";
                }
            }
            
            if (del) { //prepare effect filer
                var filter=ThroneOptions.SalvageV2.EffectFilter;
                var itemEffectPercent = [];
                var noneWithPercent=true;
                var nonChecked=true; var noneChecked1=true; var noneChecked2=true; var noneChecked3=true;
                for (i in unsafeWindow.cm.thronestats.effects) {
                    itemEffectPercent[i] = 0;
                    if(typeof(filter[i])=='undefined') ThroneOptions.SalvageV2.EffectFilter[i]={IsEnabled:false,IsEnabled2:false,IsEnabled3:false,Value:''};
                    if(typeof(filter[i].IsEnabled ) == "undefined" || filter[i].IsEnabled ===null) filter[i].IsEnabled =false;
                    if(typeof(filter[i].IsEnabled2) == "undefined" || filter[i].IsEnabled2===null) filter[i].IsEnabled2=false;
                    if(typeof(filter[i].IsEnabled3) == "undefined" || filter[i].IsEnabled3===null) filter[i].IsEnabled3=false;
                    if(typeof(filter[i].Percent   ) == "undefined" || filter[i].Percent   ===null) filter[i].Percent   ='';
                    if(filter[i].IsEnabled ) noneChecked1=false;
                    if(filter[i].IsEnabled2) noneChecked2=false;
                    if(filter[i].IsEnabled3) noneChecked3=false;
                    if(filter[i].Percent!='') noneWithPercent=false;
                }
                noneChecked = noneChecked1 && noneChecked2 && noneChecked3;
                
                var effectMode1=ThroneOptions.SalvageV2.EffectMode;
                var effectMode2=ThroneOptions.SalvageV2.EffectMode2;
                var effectMode3=ThroneOptions.SalvageV2.EffectMode3;
                if(del && (effectMode1==100 || (effectMode1<100 && noneChecked1)) && (effectMode2==100 || (effectMode2==100 && noneChecked2)) && (effectMode3==100 || (effectMode3<100 && noneChecked3)) && noneWithPercent) {
                    del=false; keepReason = "No effect selected"; //TODO multilang 
                } 
            }            
            
            if (del && !noneChecked1 && ThroneOptions.SalvageV2.EffectMode  <100) { // Effect Filter 1
                // 0 - mind. 1 von den letzten 3 Effekten
                // 2 - mind. 1 von den letzten 2 Effekten
                // 4 - mind. Letzter Effekt
                // 7 - mind. die letzten 2 Effekte
                // 8 - mind. die letzten 3 Effekte
                effectIndex3 = 0;
                effectIndex4 = 0;
                effectIndex5 = 0;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot3"].id].IsEnabled) effectIndex3 = 1;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot4"].id].IsEnabled) effectIndex4 = 3;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot5"].id].IsEnabled) effectIndex5 = 5;
                countEffect = effectIndex3 + effectIndex4 + effectIndex5;
                if (countEffect > ThroneOptions.SalvageV2.EffectMode) {
                    del = false;
                    keepReason = "Number of matching effects #A"; //TODO multilang
                }
            }
            if (del && !noneChecked2 && ThroneOptions.SalvageV2.EffectMode2 <100) { // Effect Filter 2
                // 0 - mind. 1 von den letzten 3 Effekten
                // 2 - mind. 1 von den letzten 2 Effekten
                // 4 - mind. Letzter Effekt
                // 7 - mind. die letzten 2 Effekte
                // 8 - mind. die letzten 3 Effekte
                effectIndex3 = 0;
                effectIndex4 = 0;
                effectIndex5 = 0;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot3"].id].IsEnabled2) effectIndex3 = 1;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot4"].id].IsEnabled2) effectIndex4 = 3;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot5"].id].IsEnabled2) effectIndex5 = 5;
                countEffect = effectIndex3 + effectIndex4 + effectIndex5;
                if (countEffect > ThroneOptions.SalvageV2.EffectMode2) {
                    del = false;
                    keepReason = "Number of matching effects #B"; //TODO multilang
                }
            }
            if (del && !noneChecked3 && ThroneOptions.SalvageV2.EffectMode3 <100) { // Effect Filter 3
                // 0 - mind. 1 von den letzten 3 Effekten
                // 2 - mind. 1 von den letzten 2 Effekten
                // 4 - mind. Letzter Effekt
                // 7 - mind. die letzten 2 Effekte
                // 8 - mind. die letzten 3 Effekte
                effectIndex3 = 0;
                effectIndex4 = 0;
                effectIndex5 = 0;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot3"].id].IsEnabled3) effectIndex3 = 1;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot4"].id].IsEnabled3) effectIndex4 = 3;
                if (ThroneOptions.SalvageV2.EffectFilter[item.effects["slot5"].id].IsEnabled3) effectIndex5 = 5;
                countEffect = effectIndex3 + effectIndex4 + effectIndex5;
                if (countEffect > ThroneOptions.SalvageV2.EffectMode3) {
                    del = false;
                    keepReason = "Number of matching effects #C"; //TODO multilang
                }
            }
            if (del) { // Effect Percent Filter
                // if(count==47) GM_log("item effects: "+item.effects["slot1"].id+","+item.effects["slot2"].id+","+item.effects["slot3"].id+","+item.effects["slot4"].id+","+item.effects["slot5"].id)    
                
                item_level = item.level;
                item_quality = item.quality;
                item_type = item.type;
                for (iEffect = 1; iEffect <= 5; iEffect++) {
                    effect_id = item.effects["slot" + iEffect].id;

                    effect_tier = parseInt(item.effects["slot" + iEffect].tier);
                    p = unsafeWindow.cm.thronestats.tiers[effect_id][effect_tier];
                    effect_value = p.base + ((item_level * item_level + item_level) * p.growth * 0.5);
                    itemEffectPercent[effect_id] += effect_value;
                }
                
                for (iEffect in unsafeWindow.cm.thronestats.effects) {
                    effect_name = unsafeWindow.cm.thronestats.effects[iEffect]["1"];
                    
                    if(item_type=='advisor' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor != ''){
                        if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor) == 0.0) {
                            if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
                                del = false;
                                keepReason = "Advisor " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                                break;
                            }
                        } else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor)) {
                            del = false;
                            keepReason = keepReason = "Advisor " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentAdvisor + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                            break;
                        }                    
                    }else if(item_type=='banner' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner != ''){
                        if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner) == 0.0) {
                            if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
                                del = false;
                                keepReason = "Banner " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                                break;
                            }
                        } else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner)) {
                            del = false;
                            keepReason = keepReason = "Banner " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentBanner + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                            break;
                        }        
                    }else if(item_type=='chair' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair != ''){
                        if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair) == 0.0) {
                            if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
                                del = false;
                                keepReason = "Chair " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                                break;
                            }
                        } else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair)) {
                            del = false;
                            keepReason = keepReason = "Chair " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentChair + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                            break;
                        }
                    }else if(item_type=='table' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable != ''){
                        if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable) == 0.0) {
                            if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
                                del = false;
                                keepReason = "Table " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                                break;
                            }
                        } else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable)) {
                            del = false;
                            keepReason = keepReason = "Table " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTable + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                            break;
                        }    
                    }else if(item_type=='window' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow != ''){
                        if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow) == 0.0) {
                            if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
                                del = false;
                                keepReason = "Window " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                                break;
                            }
                        } else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow)) {
                            del = false;
                            keepReason = keepReason = "Window " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentWindow + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                            break;
                        }    
                    }else if(item_type=='trophy' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy != ''){
                        if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy) == 0.0) {
                            if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
                                del = false;
                                keepReason = "Trophy " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                                break;
                            }
                        } else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy)) {
                            del = false;
                            keepReason = keepReason = "Trophy " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentTrophy + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                            break;
                        }    
                    }else if(item_type=='candelabrum' && ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum != ''){
                        if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum) == 0.0) {
                            if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
                                del = false;
                                keepReason = "Candelabrum " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                                break;
                            }
                        } else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum)) {
                            del = false;
                            keepReason = keepReason = "Candelabrum " + ThroneOptions.SalvageV2.EffectFilter[iEffect].PercentCandelabrum + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                            break;
                        }    
                    }
                    
                    if (del && ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent != '') {
                        // GM_log("EffectPercentFilter "+ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent +" =? "+itemEffectPercent[iEffect] +" ==0? "+(ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent == 0)+ " "+(Math.abs(itemEffectPercent[iEffect]) > 0.0));
                        if (Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent) == 0.0) {
                            if(Math.abs(itemEffectPercent[iEffect]) > 0.0){
                                del = false;
                                keepReason = ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                                break;
                            }
                        } else if (Math.abs(itemEffectPercent[iEffect]) >= Math.abs(ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent)) {
                            del = false;
                            keepReason = ThroneOptions.SalvageV2.EffectFilter[iEffect].Percent + "% " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect + " " + effect_name + " " + culang.throneStuffSalvagePreviewKeepReasonPercentEffect2 + "";
                            break;
                        }
                    }
                }
            }
            if (false) { // KSX DRAFT "ThroneItemDeleteFilter" (no configuration UI)
                var effectCount = [];
                for (i in unsafeWindow.cm.thronestats.effects) effectCount[i] = 0;
                for (i = 1; i <= 5; i++) effectCount[item.effects["slot" + i].id] += 1;

                if (effectCount[ 1] + effectCount[18] >= 4) del = false; // Attack + Defense Debuff
                if (effectCount[ 2] + effectCount[17] >= 4) del = false; // Defense + Attack Debuff
                if (effectCount[91] + effectCount[93] >= 2) del = false; // Chance to Find Items + Chance to Find Items in PvP
                if (effectCount[25] + effectCount[26] >= 3) del = false; // Infantry Defense + Infantry Life
                if (effectCount[ 1] >= 4) del = false; // Attack                                | A
                if (effectCount[ 2] >= 4) del = false; // Defense                            |   D
                if (effectCount[ 4] >= 3) del = false; // Combat Speed
                if (effectCount[ 5] >= 2) del = false; // Range                                | A D
                if (effectCount[ 6] >= 3) del = false; // Load                                | A    *
                if (effectCount[16] >= 2) del = false; // Bonus to Wall
                if (effectCount[17] >= 4) del = false; // Attack Debuff                        |   D
                if (effectCount[18] >= 4) del = false; // Defense Debuff                        | A
                if (effectCount[20] >= 2) del = false; // Combat Speed Debuff
                if (effectCount[21] >= 2) del = false; // Range Debuff                        | A D
                if (effectCount[25] >= 2) del = false; // Infantry Defense                    |   D
                if (effectCount[26] >= 2) del = false; // Infantry Life                        | A D
                if (effectCount[34] >= 2) del = false; // Ranged Attack                        | A
                if (effectCount[37] >= 2) del = false; // Ranged Range                        | A
                if (effectCount[45] >= 2) del = false; // Horsed Defense                        |   D
                if (effectCount[46] >= 2) del = false; // Horsed Life                        | A D
                if (effectCount[58] >= 2) del = false; // Siege Range                        | A D
                if (effectCount[59] >= 2) del = false; // Siege Load                            | A   *
                if (effectCount[68] >= 1) del = false; // Attack March Speed                    | A
                if (effectCount[77] >= 2) del = false; // Troop Training Speed                |     *
                if (effectCount[91] >= 2) del = false; // Chance to Find Items                | A   *
                if (effectCount[92] >= 2) del = false; // Chance to Find Items in Dark Forests     *
                if (effectCount[93] >= 2) del = false; // Chance to Find Items in PvP        | A   *

            }

            if(!del && ThroneOptions.SalvageV2.DeleteXitems.IsEnabled &&
                count>freeRowItems-parseIntNan(ThroneOptions.SalvageV2.DeleteXitems.Value) &&
                isInFreeRow
                ){
                del = true;keepReason="Delete last "+ThroneOptions.SalvageV2.DeleteXitems.Value+" items";
            }

            if (t.SalvagePreviewMode) {
                if (del) {
                    var effects = unsafeWindow.cm.thronestats.effects;
                    var msg = (getThroneItemName(item.id) + " (" + effects[item.effects["slot1"].id]["1"] + "/" + effects[item.effects["slot2"].id]["1"] + "/" + effects[item.effects["slot3"].id]["1"] + "/" + effects[item.effects["slot4"].id]["1"] + "/" + effects[item.effects["slot5"].id]["1"] + ")");
                    //salvageMsgs+=msg+"\n";
                    if (false) GM_log(count + " DELETE: " + msg);
                    t.addToSalvagePreviewList(count, msg, -1, isInFreeRow, del, keepReason);
                } else if (true) { //DEBUG ONLY
                    var effects = unsafeWindow.cm.thronestats.effects;
                    var msg = (getThroneItemName(item.id) + " (" + effects[item.effects["slot1"].id]["1"] + "/" + effects[item.effects["slot2"].id]["1"] + "/" + effects[item.effects["slot3"].id]["1"] + "/" + effects[item.effects["slot4"].id]["1"] + "/" + effects[item.effects["slot5"].id]["1"] + ")");
                    //salvageMsgs+=msg+"\n";
                    if (false) GM_log(count + " KEEP: " + msg);
                    t.addToSalvagePreviewList(count, msg, -1, isInFreeRow, del, keepReason);
                }
            } else {
                if (del) {
                    t.SalvageArray.push(item.id);
                }
            }
        }

        //if(true){GM_log("Items to delete:\n"+salvageMsgs);}

        if(t.SalvagePreviewMode){
            t.PaintSalvagePreview();
        } else {
            if (t.SalvageArray.length == 0) {
                t.SalvageRunning = false;
                actionLog(""+culang.tabLabelThrone+"",""+culang.throneStuffNoItemToDelete+" "+ThroneOptions.IntervalMin+" "+culang.throneStuffNoItemToDelete2+"");
                t.timersalvage = setTimeout(t.salvageCheck,ThroneOptions.IntervalMin*60*1000);
            } else {
                actionLog(""+culang.tabLabelThrone+"",""+culang.throneStuffSalvageStart+" "+t.SalvageArray.length+" "+culang.throneStuffSalvageStart2+"");
                setTimeout(t.doSalvage, 2000);
            }
        }
    },

    doSalvage : function(){
        var t = Tabs.ThroneStuff;
        if(!Options.ThroneDeleteItems) { clearTimeout(t.timersalvage);return; }
        //Soll es erst auf Level 1?
        if (ThroneOptions.SalvageV2.LevelP1) {
            t.doUpgradeNew();
        } else {
            t.doSalvageNew();
        }
    },    
        
    doUpgradeNew: function() {
        var t = Tabs.ThroneStuff;
        var itemID = t.SalvageArray[0];
        if (typeof(uW.kocThroneItems[itemID]) == 'object') {
            var item = uW.kocThroneItems[itemID];
        } else return;
        var cost = uW.cm.thronestats["upgrade"][1].Stones;
        var cityid = 0;
        if (ThroneOptions.CityMax) {
            var max = 0;
            for (var k in Cities.byID) {
                if (parseInt(Seed.resources["city"+k]["rec5"][0]) > max) {
                    max = parseInt(Seed.resources["city"+k]["rec5"][0]);
                    if (parseInt(Seed.resources["city"+k]["rec5"][0]) > cost) {
                        cityid = k;
                    }
                }
            }
            
        } else {
            for (var k in Cities.byID) {
                if (parseInt(Seed.resources["city"+k]["rec5"][0]) > cost)    {
                    cityid = k;
                    break;
                }
            }
        }
        if(cityid == 0){
            //in keiner Stadt sind genug Aethersteine vorhanden
            if (ById('ShowStatus')) ById('ShowStatus').innerHTML = "<i>"+culang.throneStuffEUQueueNoAetherstone+"</i>";
            return;
        }

        var params = uW.Object.clone(uW.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'upgradeLevel';
        params.throneRoomItemId = itemID;
        params.buffItemId = 0;
        params.payment = "aetherstone";
        params.cityId = cityid;
        new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch53.php" + uW.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                    if (rslt.gems > 0){
                        //Edelsteine wurden verwendet
                        
                    }
                    Seed.resources["city" +cityid]["rec5"][0] -= rslt.aetherstones;
                    if (rslt.success) {
                        //war ok, kann geloescht werden
                        item.level = rslt.item.level;
                        item.quality = rslt.item.quality;
                        item.name = item.createName(); 
                        uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
                        setTimeout(t.doSalvageNew, 2500);
                        return;
                    } else {
                        //hat nicht geklappt
                        item.isBroken = true;
                        item.brokenType = "level";
                        item.status = rslt.item.status;
                        item.name = item.createName(); 
                        t.SalvageArray.splice(0,1);
                        uW.cm.ThroneView.renderInventory(uW.kocThroneItems);
                    }
                } else {
                    //Fehler
                    t.SalvageArray.splice(0,1);
                }
                if (t.SalvageArray.length > 0) {
                    setTimeout(t.doSalvage, 5000);
                } else {
                    t.SalvageRunning = false;
                    t.salvageCheck();
                }
                return;
            },
            onFailure: function () {
                //Schwerer Fehler
                t.SalvageArray.splice(0,1);
                if (t.SalvageArray.length > 0) {
                    setTimeout(t.doSalvage, 5000);
                } else {
                    t.SalvageRunning = false;
                    t.salvageCheck();
                }
                return;
            },
        });
    },
        
    doSalvageNew: function() {
        var t = Tabs.ThroneStuff;
        var cityid = 0;
        if (ThroneOptions.SalvageV2.CityMin) {
            var min = 99999999;
            for (var i in Cities.byID) {
                if (parseInt(Seed.resources["city"+i]["rec5"][0]) < min) {
                    min = parseInt(Seed.resources["city"+i]["rec5"][0]);
                    cityid = i;
                }
            }
        } else {
            for (var i in Cities.byID) {
                if (parseInt(Seed.resources["city"+i]["rec5"][0]) < 950000) {
                    cityid = i;
                    break;
                }
            }
            if (cityid == 0) {
                //Keine Stadt hat weniger als 950k Aether. Es wird die 1. Stadt verwendet
                cityid = Seed.cities[0][0];
            }
        }
        
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'salvage';
        params.itemId = t.SalvageArray[0];
        params.cityId = cityid;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                try{
                    var rslt = eval("(" + transport.responseText + ")");
                    if(rslt.ok){
                        var item =  unsafeWindow.kocThroneItems[params.itemId];
                        var effects = unsafeWindow.cm.thronestats.effects;
                        var msg = (getThroneItemName(item.id) + " (" + effects[item.effects["slot1"].id]["1"] + "/"+ effects[item.effects["slot2"].id]["1"]+ "/"+ effects[item.effects["slot3"].id]["1"]+ "/"+ effects[item.effects["slot4"].id]["1"]+ "/"+ effects[item.effects["slot5"].id]["1"] +")");
                        t.addToSalvageLog(msg,rslt.aetherstones);
                        uW.kocThroneItems[params.itemId].salvage();
                    }
                    else {
                        t.addToSalvageLog(""+culang.throneStuffSalvageFaild+"",0);
                    }
                } catch(err){
                    t.addToSalvageLog(""+culang.throneStuffSalvageFaild+"",0);
                }
            },
            onFailure: function () {
                t.addToSalvageLog(""+culang.throneStuffSalvageFaild+"",0);
                return;
            },
        });
        t.SalvageArray.splice(0,1);
        t.LastDeleted = params.itemId;
        if (t.SalvageArray.length > 0) {
            setTimeout(t.doSalvage, 5000);
        } else {
            t.SalvageRunning = false;
            t.salvageCheck();
        }
    },
    


    
    hide : function (){
    },

    show : function (){
        var t = Tabs.ThroneStuff;
        if (t.curTabName == 'Sal')
            t.Salvage();
        else if (t.curTabName == 'UE')
            t.Upgrade_Enhance();
        else if (t.curTabName == 'RE')
            t.autorepair();
        else if (t.curTabName == 'ST')
            t.Stats();
        else if (t.curTabName == 'EQ') {
            t.Equip();
            for (k in t.EquipType) {
                var y = t.EquipType[k];
                if (typeof(y) == "string") {
                    what = y.toLowerCase();
                    t.paintEquipInfo(document.getElementById(what).value,what)
                }
            }
        }
    },
    autorepair:function() {
        var t = Tabs.ThroneStuff;
        var  m= '<DIV class=pdxStat>'+culang.throneStuffRepairHead+'</div><TABLE class=pdxTab width=750><tr><td></table><TABLE class=pdxTab width=98%><TR>';
        if (Options.salvageconfig.Repairrunning == true) {
            m += '<TD><INPUT id=KsTroneRepairEnable type=submit value="'+culang.throneStuffRepair+' = '+culang.buttonON+'"></td>';
        }
        else {
            m += '<TD><INPUT id=KsTroneRepairEnable type=submit value="'+culang.throneStuffRepair+' = '+culang.buttonOFF+'"></td>';
        }

        m+='<td><i>'+culang.throneStuffRepairAll+'<bR><font color=red>'+culang.throneStuffRepairAll2+'</font></i></td><tr></table>';


        t.Overv.innerHTML = m;

        ById('KsTroneRepairEnable').addEventListener ('click', function(){t.toggleRepairon(this);}, false);
    },
    toggleRepairon: function(obj){
        if (ThroneOptions.Active) {
            alert(culang.throneStuffUERunningNotPossible);
            return;
        }
        var t = Tabs.ThroneStuff;
        obj = ById('KsTroneRepairEnable');
        if (Options.salvageconfig.Repairrunning == true) {
            Options.salvageconfig.Repairrunning = false;
            if (obj) obj.value = culang.throneStuffRepair+' = '+culang.buttonOFF;
        }
        else {
            Options.salvageconfig.Repairrunning = true;
            if (obj) obj.value = culang.throneStuffRepair+' = '+culang.buttonON;

            RepairAuto.init();
        }
        saveOptions ();
    },
}
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Farm.js">
/************************************************************************************
 *                        KOC POWER - TABS FARM                                        *
 ************************************************************************************/
Tabs.farm = { //TODO rename to Farm
    tabLabel: culang.tabLabelAutoFarm,
    tabOrder : TabOptions.toFarm,
    myDiv : null,
    MapAjax : new CMapAjax(),
    popFirst : true,
    opt : {},
    nextattack : null,
    updateSeedTimer: null,
    searchRunning : false,
    tilesSearched : 0,
    tilesFound : 0,
    curX : 0,
    curY : 0,
    lastX : 0,
    firstX : 0,
    firstY : 0,
    lastY : 0,
    rallypointlevel:0,
    knt:{},
    helpArray:{},
    FarmArray:{},
    marchArray:[],
    lookup:1,
    city:0,
    deleting:false,
    DipArray: ["friendly","hostile","friendlyToThem","friendlyToYou","neutral","unallied"],
    interval: ["Continuously","1 Hour","2 Hours","3 Hours","6 Hours","12 Hours","24 Hours"],

    init : function (div){
        var t = Tabs.farm;
        t.myDiv = div;
try {
        if (FarmOptions.Troops[13] == undefined) FarmOptions.Troops[13] = 0;
        if (FarmOptions.Troops[14] == undefined) FarmOptions.Troops[14] = 0;
        if (FarmOptions.Troops[15] == undefined) FarmOptions.Troops[15] = 0;
        
        if(typeof(Seed.allianceDiplomacies)=='undefined'){
            t.myDiv.innerHTML ='<BR><CENTER><i><b>'+culang.playerMustInAlliance+'</i></b></center>';
            return;
        }

        var m = '<DIV id=pbFarmTab class=pdxStat>'+culang.farmHead+'</div><TABLE id=pbFarmOptions width=100% height=0% class=pdxTab><TR align="center">';
        if (FarmOptions.Running == false) {
            m += '<TD><INPUT id=FarmAttSearch type=submit value="'+culang.farmButton+' = '+culang.buttonOFF+'"></td>';
        } else {
            m += '<TD><INPUT id=FarmAttSearch type=submit value="'+culang.farmButton+' = '+culang.buttonON+'"></td>';
        }
        m +='<TD title="'+culang.farmShowNote+'"><INPUT id=pbpaintFarms type=submit value="'+culang.farmShow+'">';
        m += '<SELECT id=pbFarmcity type=list></td></tr></table>';
        m += '</tr></table></div>';

        m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.farmHeadStats+'</div>';

        m += '<TABLE id=pbfarmstats width=95% height=0% class=pdxTab><TR align="left"><TR>';
        for(i=0;i<Seed.cities.length;i++){
            m += '<TD>' + Seed.cities[i][1] +'</td>';
        }
        m+='</tr><TR>';
        for(i=0;i<Seed.cities.length;i++){
            m += '<TD><DIV><span id='+ 'pdtotalFarm' + i +'></span></div></td>';
        }
        m+='</tr><TR>';
        for(i=0;i<Seed.cities.length;i++){
            m += '<TD><DIV><span id='+ 'pddataFarm' + i +'></span></div></td>';
        }
        m+='</tr><TR>'
        for(i=0;i<Seed.cities.length;i++){
            m += '<TD><DIV><span id='+ 'pddataFarmarray' + i +'></span></div></td>';
        }
        m+='</tr></table>';

        m+='<DIV id=FarmCheck></div>';

        m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.farmHeadOptions+'</div>';
        m += '<TABLE id=pbfarmstats width=90% height=0% class=pdxTab>';
        m += '<TR><TD width=180>'+culang.farmKeepRP+' </td><TD><INPUT id=FarmRallyClip type=text size=2 maxlength=2 value=' + FarmOptions.RallyClip +'> '+culang.farmKeepRP2+'</td></tr>';
        m += '<TR><TD>'+culang.farmIntervall+'</td><TD><SELECT id=FarmInterval type=list></td></tr>';
        m += '<TR><TD>'+culang.farmDeleteRpt+'</td><TD><INPUT id=FarmReports type=checkbox '+(FarmOptions.DeleteReports?'CHECKED':'')+'></td><tr>';
        m += '<TR><TD>'+culang.farmSearchDist+'</td><TD><INPUT type=text id=FarmRadius size=3 maxlength=3 value='+ FarmOptions.MaxDistance +'><INPUT id=FarmSearch type=submit value="'+culang.farmSearch+'"></td><tr>';
        m += '<TR><TD>'+uW.g_js_strings.commonstr.might+':</td>';
        m += '<TD width=50>'+culang.shortMin+': <INPUT type=text id=FarmMinMight size=8 maxlength=8 value='+ FarmOptions.MinMight +'></td>';
        m += '<TD>'+culang.shortMax+': <INPUT type=text id=FarmMaxMight size=9 maxlength=9 value='+ FarmOptions.MaxMight +'></td></tr>';
        m += '<TR><TD>'+culang.farmInactivePlayer+' </td>';
        m += '<TD><INPUT type=text id=FarmInactive size=3 value='+ FarmOptions.Inactive +'> '+culang.farmInactivePlayer2+'</td></table>';
        m += '<TABLE id=pbfarmstats width=90% height=0% class=pdxTab><TR align="left"><TR><TD width=100>'+culang.mainCity+':</td>';
        for (i=1;i<=Seed.cities.length;i++) {
            m+='<TD class=pbCityEn><INPUT id=CityEnable'+ i +'  type=checkbox '+(FarmOptions.CityEnable[i]?'CHECKED':'')+'>'+ Seed.cities[i-1][1] +'</td>';
        }
        m += '</tr></table><TABLE id=pbfarmstats width=90% height=0% class=pdxTab><TR align="left"><TD width=100>'+culang.farmCityLevel+'</td>';
        for (i=1;i<=12;i++) {
            m+='<TD class=pbCityOpt><INPUT id=CityLevel'+ i +'  type=checkbox '+(FarmOptions.CityLevel[i]?'CHECKED':'')+'>'+ i +'</td>';
        }
        m += '</tr></table><TABLE id=pbfarmstats width=90% height=0% class=pdxTab><TR align="left"><TR><TD width=100>'+culang.farmDip+'</td>';
        for (i=0;i<t.DipArray.length;i++) {
            m+='<TD class=pbDipOpt><INPUT id=Diplomacy'+ t.DipArray[i] +'  type=checkbox '+(FarmOptions.Diplomacy[t.DipArray[i]]?'CHECKED':'')+'>'+ t.DipArray[i] +'</td>';
        }
        m+='</tr></table>';

        m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.farmHeadTroops+'</div>';
        m += '<TABLE id=pbaddreasignroute width=100% height=0% class=pdxTab><TR align="center">';
        m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_1_50.jpg"></td>';
        m += '<TD valign=bottom>'+culang.supplytroop+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.militiaman+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.scout+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.pikeman+'</td></tr>'
        m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop1  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[1] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop2  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[2] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop3  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[3] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop4  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[4] +'\></td></tr>';
        m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_50.jpg"></td>';
        m += '<TD valign=bottom>'+culang.swordsman+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.archer+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_7_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.cavalry+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_8_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.heavycavalry+'</td></tr>'
        m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop5  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[5] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop6  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[6] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop7  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[7] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop8  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[8] +'\></td></tr>';
        m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_50.jpg"></td>';
        m += '<TD valign=bottom>'+culang.supplywagon+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.ballista+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.batteringram+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_50.jpg"></td>'
        m += '<TD valign=bottom>'+culang.catapult+'</td></tr>'
        m += '<TR><TD  class=pbTroopOpt><INPUT id=FarmTroop9  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[9] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop10  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[10] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop11  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[11] +'\></td>';
        m += '<TD  class=pbTroopOpt><INPUT id=FarmTroop12 type=text size=10 maxlength=10 value='+ FarmOptions.Troops[12] +'\></td>';
        m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_13_50_s34.jpg"></td>';
        m += '<TD valign=bottom>'+culang.bloodthorn+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_14_50_s34.jpg"></td>'
        m += '<TD valign=bottom>'+culang.executioner+'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_15_50_s34.jpg"></td>'
        m += '<TD valign=bottom>'+culang.siegewall+'</td>'
        m += '<TD rowspan="2">&nbsp;</td>'
        m += '<TD valign=bottom>&nbsp;</td></tr>'
        m += '<TR><TD class=pbTroopOpt><INPUT id=FarmTroop13  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[13] +'\></td>';
        m += '<TD class=pbTroopOpt><INPUT id=FarmTroop14  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[14] +'\></td>';
        m += '<TD class=pbTroopOpt><INPUT id=FarmTroop15  type=text size=10 maxlength=10 value='+ FarmOptions.Troops[15] +'\></td>';
        m += '<TD  class=pbTroopOpt>&nbsp;</td>';
        m += '</tr></table>';

        t.myDiv.innerHTML = m;
        t.checkFarmData();
        if(t.nextattack == null) t.nextattack = setInterval(t.getnextCity, FarmOptions.SendInterval*1000);
        setInterval(t.startdeletereports,(120000));
        t.checkMarches();
        setInterval( t.checkMarches ,2000);
        document.getElementById('pbFarmcity').options.length=0;
        for (i=0;i<Seed.cities.length;i++){
            var o = document.createElement("option");
            o.text = Seed.cities[i][1]
            o.value = i+1;
            document.getElementById("pbFarmcity").options.add(o);
        }
        document.getElementById('FarmInterval').options.length=0;
        for (i=0;i<t.interval.length;i++){
            var o = document.createElement("option");
            o.text = t.interval[i];
            o.value = i;
            document.getElementById("FarmInterval").options.add(o);
        }
        document.getElementById('FarmInterval').value = FarmOptions.Interval;
        for(i=0;i<Seed.cities.length;i++){
            var elem = 'pdtotalFarm'+i;        
            if (t.FarmArray[i+1] == undefined) {
                document.getElementById(elem).innerHTML = '<i>'+culang.farmNoData+'</i>';
            } else {
                document.getElementById(elem).innerHTML =  ''+culang.farmFarms+' ' + t.FarmArray[i+1].length +'/'+ t.helpArray[i+1].length;
            }
        }
        document.getElementById('FarmInterval').addEventListener('change', function(){
            FarmOptions.Interval = document.getElementById('FarmInterval').value;
            saveFarmOptions();
        } , false);
        document.getElementById('FarmRallyClip').addEventListener('change', function(){
            FarmOptions.RallyClip = document.getElementById('FarmRallyClip').value;
            saveFarmOptions();
        } , false);
        document.getElementById('FarmReports').addEventListener('change', function(){
            FarmOptions.DeleteReports = document.getElementById('FarmReports').checked;
            saveFarmOptions();
        } , false);
        document.getElementById('FarmRadius').addEventListener('change', function(){
            FarmOptions.MaxDistance = parseInt(document.getElementById('FarmRadius').value);
            saveFarmOptions();
        } , false);
        document.getElementById('FarmAttSearch').addEventListener('click', function(){t.toggleBarbState(this)} , false);
        document.getElementById('FarmSearch').addEventListener('click', function(){
            for (i=1;i<=Seed.cities.length;i++) GM_deleteValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId());
            for(i=0;i<Seed.cities.length;i++){
                var elem = 'pdtotalFarm'+i;
                document.getElementById(elem).innerHTML = '<i>'+culang.farmNoData+'</i>';
            }
            t.checkFarmData();
        } , false);
        document.getElementById('pbpaintFarms').addEventListener('click', function(){t.showFarms(document.getElementById("pbFarmcity").value,Seed.cities[document.getElementById("pbFarmcity").value -1][1]);},false);

        document.getElementById('FarmMinMight').addEventListener('change', function(){
            FarmOptions.MinMight = parseInt(document.getElementById('FarmMinMight').value);
            t.FilterFarms();
            saveFarmOptions();
        } , false);
        document.getElementById('FarmMaxMight').addEventListener('change', function(){
            FarmOptions.MaxMight = parseInt(document.getElementById('FarmMaxMight').value);
            t.FilterFarms();
            saveFarmOptions();
        } , false);
        document.getElementById('FarmInactive').addEventListener('change', function(){
            FarmOptions.Inactive = parseInt(document.getElementById('FarmInactive').value);
            t.FilterFarms();
            saveFarmOptions();
        } , false);

        var element = document.getElementsByClassName('pbTroopOpt');
        for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                for (i=1;i<=15;i++){
                    FarmOptions.Troops[i] = document.getElementById('FarmTroop' + i).value;
                    saveFarmOptions();
                }
            }, false);
        }

        element = document.getElementsByClassName('pbCityOpt');
        for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                for (i=1;i<=12;i++){
                    FarmOptions.CityLevel[i] = document.getElementById('CityLevel' + i).checked;
                    saveFarmOptions();
                }
                t.FilterFarms();
            }, false);
        }

        element = document.getElementsByClassName('pbCityEn');
        for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                for (i=1;i<=Seed.cities.length;i++){
                    FarmOptions.CityEnable[i] = document.getElementById('CityEnable' + i).checked;
                    saveFarmOptions();
                }
                t.FilterFarms();
            }, false);
        }

        element = document.getElementsByClassName('pbDipOpt');
        for (k=0;k<element.length;k++){
            element[k].addEventListener('change', function(){
                for (i=0;i<t.DipArray.length;i++){
                    FarmOptions.Diplomacy[t.DipArray[i]] = document.getElementById('Diplomacy' + t.DipArray[i]).checked;
                    saveFarmOptions();
                }
                t.FilterFarms();
            }, false);

        }
} catch (ex) {
    alert(ex.name +': '+ ex.message + " @"+ ex.lineNumber);
}
    },


    checkMarches: function () {
        var t = Tabs.farm;
        for (i=0;i<FarmOptions.FarmMarches.length;i++){
            var cityId = "city"+ FarmOptions.FarmMarches[i]["cityId"];
            var city = FarmOptions.FarmMarches[i]["city"];
            var marchId = "m" + FarmOptions.FarmMarches[i]["marchId"];
            if (Seed.queue_atkp[cityId][marchId] !=undefined){
                if (Seed.queue_atkp[cityId][marchId].marchStatus == 8  && Seed.queue_atkp[cityId][marchId].hasUpdated) {
                    FarmOptions.Checks++;
                    saveFarmOptions();
                    document.getElementById('FarmCheck').innerHTML = "Attacks: " + FarmOptions.Attacks + " - Checks:" + FarmOptions.Checks;
                    for(u=1;u<=15;u++) if (parseInt(Seed.queue_atkp[cityId][marchId]["unit"+u+"Return"]) < parseInt(Seed.queue_atkp[cityId][marchId]["unit"+u+"Count"])){
                        t.FarmArray[FarmOptions.FarmMarches[i]["city"]][FarmOptions.FarmMarches[i]["number"]]["lost"] = true;
                        t.FarmArray[FarmOptions.FarmMarches[i]["city"]][FarmOptions.FarmMarches[i]["number"]]["enabled"] = false;
                    }
                    for (a=0;a<t.helpArray[FarmOptions.FarmMarches[i]["city"]].length;a++){
                        for (b=0;b<t.FarmArray[FarmOptions.FarmMarches[i]["city"]].length;b++){
                            if (parseInt(t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['x']) == parseInt(t.helpArray[FarmOptions.FarmMarches[i]["city"]][b]['x']) && parseInt(t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['y']) == parseInt(t.helpArray[FarmOptions.FarmMarches[i]["city"]][b]['y'])){
                                t.helpArray[FarmOptions.FarmMarches[i]["city"]][a]['gold'] = t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['gold'];
                                t.helpArray[FarmOptions.FarmMarches[i]["city"]][a]['resource1'] = t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['resource1'];
                                t.helpArray[FarmOptions.FarmMarches[i]["city"]][a]['resource2'] = t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['resource2'];
                                t.helpArray[FarmOptions.FarmMarches[i]["city"]][a]['resource3'] = t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['resource3'];
                                t.helpArray[FarmOptions.FarmMarches[i]["city"]][a]['resource4'] = t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['resource4'];
                                t.helpArray[FarmOptions.FarmMarches[i]["city"]][a]['empty'] = t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['empty'];
                                t.helpArray[FarmOptions.FarmMarches[i]["city"]][a]['lost'] = t.FarmArray[FarmOptions.FarmMarches[i]["city"]][b]['lost'];
                            }
                        }
                    }
                    GM_setValue('Farms_' + Seed.player['name'] + '_city_' + FarmOptions.FarmMarches[i]["city"] + '_' + getServerId(), JSON2.stringify(t.helpArray[FarmOptions.FarmMarches[i]["city"]]));
                    FarmOptions.FarmMarches.splice(i,1);
                    saveFarmOptions();
                }
            } else {
                FarmOptions.FarmMarches.splice(i,1);
                saveFarmOptions();
            }
        }
    },

    checkInactives : function (citynumber,city,FarmNumber,xcoord,ycoord,kid,uid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15){
        var t = Tabs.farm;
        var now = new Date().getTime()/1000.0;
        var hours = (now - t.FarmArray[city][FarmOptions.FarmNumber[city]]['LastCheck']) / 3600;
        if (t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive'] == "?" || hours > 6){
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.pid = uid;
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (transport) {
                    var rslt = eval("(" + transport.responseText + ")");
                    var lastLogin = rslt.playerInfo.lastLogin;
                    var fullDate = lastLogin.substr(0,4) +", "+ lastLogin.substr(5,2) +", "+ lastLogin.substr(8,2) ;
                    var time = new Date (fullDate).getTime()/1000;
                    var days = Math.floor((now - time) / 86400);
                    t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive'] = days;
                    for (i=0;i<t.helpArray[city].length;i++){
                        if (xcoord == parseInt(t.helpArray[city][i]['x']) && ycoord == parseInt(t.helpArray[city][i]['y'])){
                            t.helpArray[city][i]['DaysInactive'] = days;
                            t.helpArray[city][i]['LastCheck'] = now;
                        }
                    }
                    GM_setValue('Farms_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.helpArray[city]));
                    if (days > FarmOptions.Inactive) {
                        t.doBarb(citynumber,city,FarmNumber,xcoord,ycoord,kid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15);
                    } else     {
                        FarmOptions.FarmNumber[city]++;
                        saveFarmOptions();
                        t.barbing();
                    }
                },
                onFailure: function (rslt) {
                    notify (rslt);
                },
            });
        } else {
            if (t.FarmArray[city][FarmOptions.FarmNumber[city]]['DaysInactive'] > FarmOptions.Inactive) {
                t.doBarb(citynumber,city,FarmNumber,xcoord,ycoord,kid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15);
            } else {
                FarmOptions.FarmNumber[city]++;
                saveFarmOptions();
                t.barbing();
            }
        }
    },

    showFarms: function (citynumber,cityname) {
        var t = Tabs.farm;
        var popTradeRoutes = null;
        t.popTradeRoutes = new CPopup('pbShowFarms', 0, 0, 1100, 485, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:440px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';
        t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
        t.popTradeRoutes.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.farmFarms+' '+cityname+'</div>';
        t.paintFarms(citynumber,cityname);
        t._addTabHeader(citynumber,cityname);
        t.popTradeRoutes.show(true)    ;
    },


    ToggleFarms: function(citynumber) {
        var t = Tabs.farm;
        var id=0;
        var element_class = document.getElementsByClassName('Farm');
        for (d = 1; d <= t.FarmArray[citynumber].length; d++) {
            id = d-1;
            var ele = document.getElementById('FarmToggle' + d);
            if (ele.checked) {
                t.FarmArray[citynumber][id].enabled = true;
                t.FarmArray[citynumber][id].lost = false;
                t.FarmArray[citynumber][id].empty = 0;
            }
            else t.FarmArray[citynumber][id].enabled = false;
        }
        for (i=0;i<t.helpArray[citynumber].length;i++){
            for (j=0;j<t.FarmArray[citynumber].length;j++){
                if (parseInt(t.FarmArray[citynumber][j]['x']) == parseInt(t.helpArray[citynumber][i]['x']) && parseInt(t.FarmArray[citynumber][j]['y']) == parseInt(t.helpArray[citynumber][i]['y'])) t.helpArray[citynumber][i].enabled = t.FarmArray[citynumber][j].enabled;
            }
        }
        GM_setValue('Farms_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId(), JSON2.stringify(t.helpArray[citynumber]));
    },

    paintFarms: function(i,cityname){
        var t = Tabs.farm;
        for (k=(t.FarmArray[i].length-1);k>=0;k--){t._addTab(i,cityname,k+1,t.FarmArray[i][k]['enabled'], t.FarmArray[i][k]['x'], t.FarmArray[i][k]['y'],t.FarmArray[i][k]['dist'], t.FarmArray[i][k]['level'],t.FarmArray[i][k]['AllianceName'], t.FarmArray[i][k]['Diplomacy'], t.FarmArray[i][k]['PlayerName'], t.FarmArray[i][k]['cityName'],t.FarmArray[i][k]['might'], t.FarmArray[i][k]['cityNumber'], t.FarmArray[i][k]['attacked'],t.FarmArray[i][k]['DaysInactive'],t.FarmArray[i][k]['lost'],t.FarmArray[i][k]['empty'],t.FarmArray[i][k]['gold'],t.FarmArray[i][k]['resource1'],t.FarmArray[i][k]['resource2'],t.FarmArray[i][k]['resource3'],t.FarmArray[i][k]['resource4']);}
    },


    _addTab: function(citynumber,cityname,queueId,status,X,Y,dist,level,AllianceName,diplomacy,playerName,cityName,might,cityNumber,attacked,DaysInactive,lost,empty,gold,rec1,rec2,rec3,rec4){
        var t = Tabs.farm;
        var row = document.getElementById('pbBars').insertRow(0);
        row.vAlign = 'top';
        if (lost) row.style.color = "red";
        if (!lost && empty == 0) row.style.color = "black";
        if (FarmOptions.Inactive > DaysInactive) row.style.color = "orange";
        row.insertCell(0).innerHTML = queueId;
        row.insertCell(1).innerHTML = "<a href='javascript:void(0)' onclick='cm.utils.CoordinateLinkController.onClick(event)' class='coordinateLink'>("+X+","+Y+")</a>";
        row.insertCell(2).innerHTML = dist;
        row.insertCell(3).innerHTML = level;
        row.insertCell(4).innerHTML = AllianceName;
        row.insertCell(5).innerHTML = diplomacy;
        row.insertCell(6).innerHTML = playerName;
        row.insertCell(7).innerHTML = cityName;
        row.insertCell(8).innerHTML = addCommas(might);
        row.insertCell(9).innerHTML = DaysInactive;
        row.insertCell(10).innerHTML = attacked;
        row.insertCell(11).innerHTML = '<INPUT class=Farm id="FarmToggle' + queueId + '" type=checkbox>';

        var element_class = document.getElementsByClassName('Farm');
        for (c = 0; c < element_class.length; c++) {
            element_class[c].checked = t.FarmArray[citynumber][c].enabled;
            element_class[c].addEventListener('click', function(){t.ToggleFarms(citynumber)}, false);
        }
    },

    _addTabHeader: function(citynumber,cityname) {
        var t = Tabs.farm;
        var row = document.getElementById('pbBars').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = "Id";
        row.insertCell(1).innerHTML = ""+culang.shortCoordinate+"";
        row.insertCell(2).innerHTML = ""+culang.shortDistance+"";
        row.insertCell(3).innerHTML = ""+uW.g_js_strings.commonstr.level+"";
        row.insertCell(4).innerHTML = ""+culang.farmAllianceName+"";
        row.insertCell(5).innerHTML = ""+culang.mainDiplo+"";
        row.insertCell(6).innerHTML = ""+culang.mainPlayer+"";
        row.insertCell(7).innerHTML = ""+culang.mainCity+"";
        row.insertCell(8).innerHTML = ""+uW.g_js_strings.commonstr.might+"";
        row.insertCell(9).innerHTML = ""+culang.farmInactive+"";
        row.insertCell(10).innerHTML = ""+culang.farmAttacks+"";
    },


    startdeletereports : function (){
        var t = Tabs.farm;
        if (!FarmOptions.DeleteReports) return;
        if(!t.deleting){
            t.deleting = true;
            t.fetchbarbreports(0, t.checkbarbreports);
        }
    },
    fetchbarbreports : function (pageNo, callback){
        var t = Tabs.farm;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if(pageNo > 0)
            params.pageNo = pageNo;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                callback(rslt);
            },
            onFailure: function () {
            },
        });
    },
    checkbarbreports : function (rslt){
        var t = Tabs.farm;
        if(!rslt.ok){
            return;
        }
        if(rslt.arReports.length < 1){
            return;
        }
        var reports = rslt.arReports;
        var totalPages = rslt.totalPages;
        var deletes1 = new Array();
        for(k in reports){
            for (i=1;i<=Seed.cities.length;i++){
                var x=Seed.cities[i-1]["2"];
                var y=Seed.cities[i-1]["3"];
                for (j=0;j<t.FarmArray[i].length;j++){
                    if (reports[k].side1XCoord == x && reports[k].side1YCoord == y && reports[k].side0XCoord == t.FarmArray[i][j]["x"] && reports[k].side0YCoord == t.FarmArray[i][j]["y"]) deletes1.push(k.substr(2));
                }
            }
        }
        if(deletes1.length > 0){
            t.deletereports(deletes1);
        } else {
            t.deleting = false;
            return;
        }
    },

    deletereports : function (deletes1){
        var t = Tabs.farm;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.s1rids = deletes1.join(",");
        params.s0rids = '';
        params.cityrids = '';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length);
                t.fetchbarbreports(0, t.checkbarbreports);
            },
            onFailure: function () {
            },
        });
    },

    isMyself: function(userID){
        if(!Seed.players["u"+userID])
            return false;
        if(Seed.players["u"+userID].n == Seed.player.name)
            return true;
        else
            return false;
        return false;
    },

    checkFarmData: function(){
        var t = Tabs.farm;
        for (i=1;i<=Seed.cities.length;i++){
            //GM_log("checkFarmData City "+i);
            t.helpArray[i] = [];
            if (!FarmOptions.CityEnable[i]) continue;        
            var myarray = (GM_getValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId()));
            if (myarray == undefined && t.searchRunning==false) {
                t.searchRunning = true;
                t.lookup=i;
                t.opt.startX=parseInt(Seed.cities[(i-1)][2]);
                t.opt.startY=parseInt(Seed.cities[(i-1)][3]);
                t.clickedSearch();
            }
            if (myarray != undefined){
                myarray = JSON2.parse(myarray);
                //if(AttackOptions.Method == 'distance') 
                t.helpArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
                //if(AttackOptions.Method == 'level') t.helpArray[i] = myarray.sort(function function (a,b) {a = parseInt(a['level']);b = parseInt(b['level']);return (a > b )? -1 : ((a < b ? 1 : t.SortDist(a,b)));});
                //if(AttackOptions.Method == 'lowlevel') t.helpArray[i] = myarray.sort(function function (a,b) {a = parseInt(a['level']);b = parseInt(b['level']);return (a < b )? -1 : ((a > b ? 1 : t.SortDist(a,b)));});
                GM_setValue('Farms_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(), JSON2.stringify(t.helpArray[i]));
            }
        }
        //GM_log("checkFarmData -> t.FilterFarms()");
        t.FilterFarms();
    },

    FilterFarms: function() {
        try{
            var t = Tabs.farm;
            if (t.searchRunning) return;
            t.FarmArray = new Array();
            t.FarmArray["1"] = new Array();
            t.FarmArray["2"] = new Array();
            t.FarmArray["3"] = new Array();
            t.FarmArray["4"] = new Array();
            t.FarmArray["5"] = new Array();
            t.FarmArray["6"] = new Array();
            t.FarmArray["7"] = new Array();
            t.FarmArray["8"] = new Array();
            for (u=1;u<=Seed.cities.length;u++){
                for (i=0;i<t.helpArray[u].length;i++){
                    var checkLvl = false;
                    var checkMight = false;
                    var checkDip = false;
                    var checkAlliance = false;
                    var AllianceName = "";
                    for (j=1;j<=12;j++) if (FarmOptions.CityLevel[j] && t.helpArray[u][i].level == j) checkLvl=true;
                    if (/*Seed.allianceDiplomacies!=undefinied &&*/ Seed.allianceDiplomacies.allianceName != undefined) AllianceName = Seed.allianceDiplomacies.allianceName;
                    if (t.helpArray[u][i].AllianceName != AllianceName) checkAlliance = true;
                    if (t.helpArray[u][i].might >= FarmOptions.MinMight && t.helpArray[u][i].might <= FarmOptions.MaxMight) checkMight = true;
                    for (j in FarmOptions.Diplomacy) if (FarmOptions.Diplomacy[j] && t.helpArray[u][i].Diplomacy == j) checkDip=true;
                    if (checkLvl && checkMight && checkDip && checkAlliance) t.FarmArray[u].push (t.helpArray[u][i]);
                }
                var elem = 'pdtotalFarm'+(u-1);
                if (t.FarmArray[u] == undefined) document.getElementById(elem).innerHTML = '<i>'+culang.farmNoData+'</i>';
                else document.getElementById(elem).innerHTML =  ''+culang.farmFarms+' ' + t.FarmArray[u].length +'/'+ t.helpArray[u].length;
            }
        } catch(e){
            GM_log(e.message);
        }
    },



    SortDist: function(a,b) {
        a = parseFloat(a['dist']);
        b = parseFloat(b['dist']);
        return (a < b )? -1 : ((a > b ? 1 : 0));
    },

    toggleBarbState: function(obj){
        var t = Tabs.farm;
        if (FarmOptions.Running == true) {
            FarmOptions.Running = false;
            obj.value = culang.farmButton+' = '+culang.buttonOFF;
            saveFarmOptions();
            t.nextattack = null;
            t.updateSeedTimer = null;
        } else {
            var en = false;
            for (var i=1;i<=Seed.cities.length;i++) {
                if (FarmOptions.CityEnable[i]) en = true;
            }
            if (en) {
                FarmOptions.Running = true;
                obj.value = culang.farmButton+' = '+culang.buttonON;
                saveFarmOptions();
                t.checkFarmData();
                t.nextattack = setInterval(t.getnextCity,5000);
            }
        }
    },

    barbing : function(){
        var t = Tabs.farm;
        var city = t.city;
        var u1 = FarmOptions.Troops[1];
        var u2 = FarmOptions.Troops[2];
        var u3 = FarmOptions.Troops[3];
        var u4 = FarmOptions.Troops[4];
        var u5 = FarmOptions.Troops[5];
        var u6 = FarmOptions.Troops[6];
        var u7 = FarmOptions.Troops[7];
        var u8 = FarmOptions.Troops[8];
        var u9 = FarmOptions.Troops[9];
        var u10 = FarmOptions.Troops[10];
        var u11 = FarmOptions.Troops[11];
        var u12 = FarmOptions.Troops[12];
        var u13 = FarmOptions.Troops[13];
        var u14 = FarmOptions.Troops[14];
        var u15 = FarmOptions.Troops[15];
        var now = new Date().getTime()/1000.0;
        now = now.toFixed(0);
        citynumber = Seed.cities[city-1][0];
        cityID = 'city' + citynumber;

        t.getAtkKnight(citynumber);
        var rinfo = getRallypointInfo(citynumber);
        t.rallypointlevel = rinfo.maxMarches;
        var slots = rinfo.usedSlots;
        
        var element2 = 'pddataFarmarray'+(city-1);
        document.getElementById(element2).innerHTML =  ''+culang.mainSRallyPoint+': (' + slots + '/' + t.rallypointlevel +')';

        if (!FarmOptions.CityEnable[city]) return;
        if ((t.rallypointlevel-FarmOptions.RallyClip) <= slots) return;
        if (t.knt.toSource() == "[]") return;
        if (u1 > parseInt(Seed.units[cityID]['unt1']) || 
                u2 > parseInt(Seed.units[cityID]['unt2']) || 
                u3 > parseInt(Seed.units[cityID]['unt3']) || 
                u4 > parseInt(Seed.units[cityID]['unt4']) || 
                u5 > parseInt(Seed.units[cityID]['unt5']) || 
                u6 > parseInt(Seed.units[cityID]['unt6']) || 
                u7 > parseInt(Seed.units[cityID]['unt7']) || 
                u8 > parseInt(Seed.units[cityID]['unt8']) || 
                u9 > parseInt(Seed.units[cityID]['unt9']) || 
                u10 > parseInt(Seed.units[cityID]['unt10']) || 
                u11 > parseInt(Seed.units[cityID]['unt11']) || 
                u12 > parseInt(Seed.units[cityID]['unt12']) || 
                u13 > parseInt(Seed.units[cityID]['unt13']) ||
                u14 > parseInt(Seed.units[cityID]['unt14']) ||
                u15 > parseInt(Seed.units[cityID]['unt15'])) return;
        if (FarmOptions.FarmNumber[city]>=t.FarmArray[city].length) FarmOptions.FarmNumber[city]=0;
        var kid = t.knt[0].ID;

        var interval = 0;
        switch(FarmOptions.Interval){
            case "1":interval = 1;break;
            case "2":interval = 2;break;
            case "3":interval = 3;break;
            case "4":interval = 6;break;
            case "5":interval = 12;break;
            case "6":interval = 24;break;
        }

        var check=0;
        while (check == 0){
            check=1;
            for (i=1;i<=15;i++){
                if (FarmOptions.Troops[i] > parseInt(Seed.units[cityID]['unt'+i])) check=0;
            }
            if (FarmOptions.Troops[1] == 0 && 
                    FarmOptions.Troops[2] == 0 && 
                    FarmOptions.Troops[3] == 0 && 
                    FarmOptions.Troops[4] == 0 && 
                    FarmOptions.Troops[5] == 0 && 
                    FarmOptions.Troops[6] == 0 && 
                    FarmOptions.Troops[7] == 0 && 
                    FarmOptions.Troops[8] == 0 && 
                    FarmOptions.Troops[9] == 0 &&
                    FarmOptions.Troops[10] == 0 && 
                    FarmOptions.Troops[11] == 0 && 
                    FarmOptions.Troops[12] == 0 && 
                    FarmOptions.Troops[13] == 0 &&
                    FarmOptions.Troops[14] == 0 &&
                    FarmOptions.Troops[15] == 0) check=0;
            if (!t.FarmArray[city][FarmOptions.FarmNumber[city]]['enabled']) check=0;
            if (now < (parseInt(t.FarmArray[city][FarmOptions.FarmNumber[city]]['time']) + (3600 * interval))) check=0;
            if (check ==0) FarmOptions.FarmNumber[city]++;
            if (FarmOptions.FarmNumber[city]>=t.FarmArray[city].length) {
                FarmOptions.FarmNumber[city]=0;
                break;
            }
        }
        if (check == 0) return;

        var xcoord = t.FarmArray[city][FarmOptions.FarmNumber[city]]['x'];
        var ycoord = t.FarmArray[city][FarmOptions.FarmNumber[city]]['y'];
        var uid = t.FarmArray[city][FarmOptions.FarmNumber[city]]['UserId'];
        saveFarmOptions();
        if ((t.rallypointlevel - FarmOptions.RallyClip) > slots) t.checkInactives(citynumber,city,FarmOptions.FarmNumber[city],xcoord,ycoord,kid,uid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14);
    },

    getnextCity: function(){
        var t = Tabs.farm;
        if (!FarmOptions.Running) return;
        var en = false;
        for (var i=1;i<=Seed.cities.length;i++) {
            if (FarmOptions.CityEnable[i]) en = true;
        }
        if (!en) return;
        if(t.searchRunning) return;
        do {
            var city = t.city+1;
            if (city>Seed.cities.length){
                city=1;
            }
            t.city = city;    
            en = false;
            for (var i=1;i<=Seed.cities.length;i++) {
                if (FarmOptions.CityEnable[i]) en = true;
            }
        } while (!FarmOptions.CityEnable[city] && en);
        if (en) t.barbing();
    },

    getAtkKnight : function(cityID){
        var t = Tabs.farm;
        t.knt = new Array();
        var rinfo = getRallypointInfo(cityID);
        t.rallypointlevel = rinfo.maxMarches;
        for (k in Seed.knights['city' + cityID]){
            if (Seed.knights['city' + cityID][k]["knightStatus"] == 1 && 
                    Seed.leaders['city' + cityID]["resourcefulnessKnightId"] != Seed.knights['city' + cityID][k]["knightId"] && 
                    Seed.leaders['city' + cityID]["politicsKnightId"] != Seed.knights['city' + cityID][k]["knightId"] && 
                    Seed.leaders['city' + cityID]["combatKnightId"] != Seed.knights['city' + cityID][k]["knightId"] && 
                    Seed.leaders['city' + cityID]["intelligenceKnightId"] != Seed.knights['city' + cityID][k]["knightId"]){
                t.knt.push ({
                    Name:   Seed.knights['city' + cityID][k]["knightName"],
                    Combat:    Seed.knights['city' + cityID][k]["combat"],
                    ID:        Seed.knights['city' + cityID][k]["knightId"],
                });
            }
        }
        t.knt = t.knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
    },

    doBarb: function(cityID,counter,number,xcoord,ycoord,kid,u1,u2,u3,u4,u5,u6,u7,u8,u9,u10,u11,u12,u13,u14,u15){
        var t = Tabs.farm;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid=cityID;
        params.type=4;
        params.kid=kid;
        params.xcoord = xcoord;
        params.ycoord = ycoord;
        if (u1>0) params.u1=u1;
        if (u2>0)params.u2=u2;
        if (u3>0)params.u3=u3;
        if (u4>0)params.u4=u4;
        if (u5>0)params.u5=u5;
        if (u6>0)params.u6=u6;
        if (u7>0)params.u7=u7;
        if (u8>0)params.u8=u8;
        if (u9>0)params.u9=u9;
        if (u10>0)params.u10=u10;
        if (u11>0)params.u11=u11;
        if (u12>0)params.u12=u12;
        if (u13>0)params.u13=u13;
        if (u14>0)params.u14=u14;
        if (u15>0)params.u15=u15;
        params.gold =0;
        params.r1=0;
        params.r2=0;
        params.r3=0;
        params.r4=0;
        params.r5=0;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unsafeWindow.unixtime();
                    var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                    var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                    for(i = 0; i <= unitsarr.length; i++){
                        if(params["u"+i]){
                            unitsarr[i] = params["u"+i];
                        }
                    }
                    var currentcityid = params.cid;
                    unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                    var slots=0;
                    for(var k in Seed.queue_atkp['city'+cityID]) slots++;
                    if(Seed.queue_atkp['city'+cityID].toSource() == "[]") slots = 0;
                    var element1 = 'pddataFarmarray'+(counter-1);
                    document.getElementById(element1).innerHTML =  'RP: (' + slots + '/' + t.rallypointlevel +')';
                    var now = new Date().getTime()/1000.0;
                    now = now.toFixed(0);
                    t.FarmArray[counter][number]['time'] = now;
                    t.FarmArray[counter][number]['attacked']++;
                    FarmOptions.FarmMarches.push ({city:counter,cityId:cityID,marchId:rslt.marchId,number:number});
                    FarmOptions.FarmNumber[counter]++;
                    FarmOptions.Attacks++;
                    saveFarmOptions();
                    document.getElementById('FarmCheck').innerHTML = ""+culang.farmAttacks+": " + FarmOptions.Attacks + " - "+culang.farmChecks+": " + FarmOptions.Checks;
                    for (i=0;i<t.helpArray[counter].length;i++){
                        for (j=0;j<t.FarmArray[counter].length;j++){
                            if (parseInt(t.FarmArray[counter][j]['x']) == parseInt(t.helpArray[counter][i]['x']) && parseInt(t.FarmArray[counter][j]['y']) == parseInt(t.helpArray[counter][i]['y'])){
                                t.helpArray[counter][i]['time'] = t.FarmArray[counter][j]['time'];
                                t.helpArray[counter][i]['attacked'] = t.FarmArray[counter][j]['attacked'];
                            }
                        }
                    }
                    GM_setValue('Farms_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.helpArray[counter]));
                }
            },
            onFailure: function () {}
        });
        saveFarmOptions();
    },

    clickedSearch : function (){
        var t = Tabs.farm;
        t.opt.searchType = 0;
        t.opt.maxDistance = FarmOptions.MaxDistance;
        t.opt.searchShape = 'circle';
        t.mapDat = [];
        t.firstX =  t.opt.startX - t.opt.maxDistance;
        t.lastX = t.opt.startX + t.opt.maxDistance;
        t.firstY =  t.opt.startY - t.opt.maxDistance;
        t.lastY = t.opt.startY + t.opt.maxDistance;
        t.tilesSearched = 0;
        t.tilesFound = 0;
        t.curX = t.firstX;
        t.curY = t.firstY;
        var xxx = t.MapAjax.normalize(t.curX);
        var yyy = t.MapAjax.normalize(t.curY);
        var element = 'pddataFarm'+(t.lookup-1);
        document.getElementById(element).innerHTML = ''+culang.searchSearched+' '+ xxx +','+ yyy;
        setTimeout (function(){t.MapAjax.request (xxx, yyy, 40, t.mapCallback)}, MAP_DELAY);
    },

    mapCallback : function (left, top, width, rslt){
        var t = Tabs.farm;
        if (!t.searchRunning)
            return;
        if (!rslt.ok){
            t.stopSearch (''+culang.mainError+': '+ rslt.errorMsg);
            return;
        }
        if (rslt.error_code == 9) {
            var element = 'pddataFarm'+(t.lookup-1);
            document.getElementById(element).innerHTML = 'MAP-Error (60sec): '+ left +','+ top;
            setTimeout (function(){
                var element = 'pddataFarm'+(t.lookup-1);
                document.getElementById(element).innerHTML = ''+culang.searchSearched+' '+ left +','+ top;
                t.MapAjax.request (left, top, 40, t.mapCallback);
            }, 61000);
            return;
        }
        
        var map = rslt.data;
        for (k in map){
            var dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
            var who = "u" + map[k].tileUserId;
            if (rslt.userInfo[who] == undefined) continue;
            var AllianceName = "";
            if (map[k].cityName == null && map[k].misted ==false) continue;
            if (t.isMyself(map[k].tileUserId)) continue;
            if (map[k].tileType!= 51) continue;
            
            var Diplomacy = "neutral";
            for (DipStatus in t.DipArray) {
                var AllianceId = 0;
                if (rslt.userInfo[who] != undefined) AllianceId = "a" + rslt.userInfo[who].a;
                for (alliance in Seed.allianceDiplomacies[t.DipArray[DipStatus]]) if (Seed.allianceDiplomacies[t.DipArray[DipStatus]][AllianceId] != undefined) Diplomacy = t.DipArray[DipStatus];
            }
            if (rslt.allianceNames[AllianceId] != undefined) AllianceName = rslt.allianceNames[AllianceId];
            if (Diplomacy == "neutral" && AllianceName =="") Diplomacy = "unallied";
            t.mapDat.push ({time:0,empty:0,lost:false,enabled:'true',attacked:0,DaysInactive:"?",LastCheck:0,Diplomacy:Diplomacy,UserId:map[k].tileUserId,AllianceName:AllianceName,x:map[k].xCoord,y:map[k].yCoord,dist:dist,level:map[k].tileLevel,PlayerName:rslt.userInfo[who].n,cityName:map[k].cityName,might:rslt.userInfo[who].m,cityNumber:map[k].cityNum});
        }
        t.tilesSearched += (40*40);

        t.curX += 40;
        if (t.curX > t.lastX){
            t.curX = t.firstX;
            t.curY += 40;
            if (t.curY > t.lastY){
                var element = 'pdtotalFarm'+(t.lookup-1);
                document.getElementById(element).innerHTML = ''+culang.farmFound+' ' + t.mapDat.length;
                var element = 'pddataFarm'+(t.lookup-1);
                document.getElementById(element).innerHTML = "";
                GM_setValue('Farms_' + Seed.player['name'] + '_city_' + t.lookup + '_' + getServerId(), JSON2.stringify(t.mapDat));
                t.searchRunning = false;
                for (y=1;y<=8;y++) FarmOptions.FarmNumber[y] = 0;
                t.checkFarmData();
                return;
            }
        }
        var x = t.MapAjax.normalize(t.curX);
        var y = t.MapAjax.normalize(t.curY);
        var element = 'pddataFarm'+(t.lookup-1);
        document.getElementById(element).innerHTML = ''+culang.searchSearched+' '+ x +','+ y;
        setTimeout (function(){t.MapAjax.request (x, y, 40, t.mapCallback)}, MAP_DELAY);
    },

    stopSearch : function (msg){
        var t = Tabs.farm;
        var element = 'pddataFarm'+(t.lookup-1);
        document.getElementById(element).innerHTML = msg;
        t.searchRunning = false;
    },

    hide : function (){

    },

    show : function (){

    },

};
//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/Crest.js">
/************************************************************************************
 *                        KOC POWER - TABS CREST                                        *
 ************************************************************************************/
Tabs.Crest = {
    tabOrder: TabOptions.toCrest,
    tabLabel: culang.tabLabelCrest,
    myDiv : null,
    rallypointlevel:null,
    error_code: 0,
    knt:{},

    /** window display **/
    init : function (div){
        var t = Tabs.Crest;
        Options.crestMarchError = 0;
        crestTogObj = ById('Cresttoggle');

        setInterval(t.sendCrestReport, 1*60*1000);
        setTimeout(function(){ t.Rounds(1,0,0);}, 5*1000);
        setTimeout(function() {

            if (Options.crestRunning == false) {
                if (crestTogObj) crestTogObj.value = culang.tabLabelCrest+" = "+culang.buttonOFF;
            } else {
                if (crestTogObj) crestTogObj.value = culang.tabLabelCrest+" = "+culang.buttonON;
            }

        },500);

        t.myDiv = div;
        var selbut=0;
        var m = '<DIV id=pbCrestTab class=pdxStat>'+culang.crestHead+'</div><TABLE id=pbcrestfunctions width=100% height=0% class=pdxTab>';

        m += '<TR align="left">';
        m += '<td>'+culang.mainIntervall+': <INPUT type=text size=3 value='+Options.Crestinterval+' id=pbcrest_interval /> '+culang.mainSeconds+'</td>';
        m += '<td>'+culang.crestKeepRPSlots+' <INPUT id=bocrestslot value='+Options.CrestSlot+' type=text size=2 \> '+culang.crestKeepRPSlots2+'</td>';
        m += '<td><INPUT id=showCrestTargets type=submit value="'+culang.crestRoute+'"></td>';

        if (Options.crestRunning == false) {
            m += '<TD><INPUT id=Cresttoggle type=submit value="'+culang.tabLabelCrest+' = '+culang.buttonOFF+'"></td>';
        } else {
            m += '<TD><INPUT id=Cresttoggle type=submit value="'+culang.tabLabelCrest+' = '+culang.buttonON+'"></td>';
        }
        m += '<TD><INPUT id=CrestHelp type=submit value="'+culang.buttonHelp+'"></td></tr>';

        m += '<tr><TD colspan=3><INPUT id=pbsendreport type=checkbox '+ (Options.crestreport?' CHECKED':'') +'\> '+culang.crestEnableReports+' -  &nbsp; '+culang.mainIntervall+' <INPUT id=pbsendcrestreportint value='+ Options.CrestMsgInterval +' type=text size=3 \> '+culang.mainHours+' <input type=button value="'+culang.buttonSendCrest+'" id=bosendreportnow></td></tr></table>';
        m += '<DIV id=pbOpt class=pdxStat>'+culang.crestHeadSettings+'</div>';
        m += '<DIV style="margin-bottom:10px;"><b>'+culang.mainCastle+'</b>: <span id=crestcity></span></div>';
        m += '<TABLE class=pdxTab><TR><TD><b>'+culang.mainCoord+'</b>: &nbsp;&nbsp;X:<INPUT id=pbcrestx type=text size=3 maxlength=3 value=""></td>';
        m += '<TD>Y:<INPUT id=pbcresty type=text size=3 maxlength=3 value=""></td></tr></table>';
        m += '<TABLE class=pdxTab><TR><TD>'+culang.crestWave+' <b>1</b>: </td><TD>&nbsp;&nbsp;<img src="'+IMGmiddleSupplyTroop+'"></td><TD><INPUT id=R1ST type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleMilitiaman+'"></td><TD><INPUT id=R1MM type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleScout+'"></td><TD><INPUT id=R1Scout type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddlePikeman+'"></td><TD><INPUT id=R1Pike type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleSwordsman+'"></td><TD><INPUT id=R1Sword type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleArcher+'"></td><TD><INPUT id=R1Arch type=text size=7 maxlength=6 value=0></td></tr>';
        m += '<tr><td></td><TD>&nbsp;&nbsp;<img src="'+IMGmiddleCavalry+'"></td><TD><INPUT id=R1LC type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleHeavyCavalry+'"></td><TD><INPUT id=R1HC type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleSupplyWagon+'"></td><TD><INPUT id=R1SW type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleBallista+'"></td><TD><INPUT id=R1Ball type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleBatteringRam+'"></td><TD><INPUT id=R1Ram type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleCatapult+'"></td><TD><INPUT id=R1Cat type=text size=7 maxlength=6 value=0></td></tr>';

        m += '<tr><td></td><TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50_s34.jpg"></td><TD><INPUT id=R1BT type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50_s34.jpg"></td><TD><INPUT id=R1EX type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50_s34.jpg"></td><TD><INPUT id=R1SWa type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td>';
        m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td>';
        m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td></tr>';

        m += '<tr><td>&nbsp;</td><td>&nbsp;</td></tr><tr><td>&nbsp;</td><td>&nbsp;</td></tr>';
        
        m += '<TR><TD>'+culang.crestWave+' <b>2</b>: </td><TD>&nbsp;&nbsp;<img src="'+IMGmiddleSupplyTroop+'"></td><TD><INPUT id=R2ST type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleMilitiaman+'"></td><TD><INPUT id=R2MM type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleScout+'"></td><TD><INPUT id=R2Scout type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddlePikeman+'"></td><TD><INPUT id=R2Pike type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleSwordsman+'"></td><TD><INPUT id=R2Sword type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleArcher+'"></td><TD><INPUT id=R2Arch type=text size=7 maxlength=6 value=0></td></tr>';
        m += '<tr><td></td><TD>&nbsp;&nbsp;<img src="'+IMGmiddleCavalry+'"></td><TD><INPUT id=R2LC type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleHeavyCavalry+'"></td><TD><INPUT id=R2HC type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleSupplyWagon+'"></td><TD><INPUT id=R2SW type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleBallista+'"></td><TD><INPUT id=R2Ball type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleBatteringRam+'"></td><TD><INPUT id=R2Ram type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img src="'+IMGmiddleCatapult+'"></td><TD><INPUT id=R2Cat type=text size=7 maxlength=6 value=0></td></tr>';

        m += '<tr><td></td><TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50_s34.jpg"></td><TD><INPUT id=R2BT type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50_s34.jpg"></td><TD><INPUT id=R2EX type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;<img width=30 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50_s34.jpg"></td><TD><INPUT id=R2SWa type=text size=7 maxlength=6 value=0></td>';
        m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td>';
        m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td>';
        m += '<TD>&nbsp;&nbsp;</td><TD>&nbsp;</td></tr>';
        
        m += '</table>';
        m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRouteCrest type=submit value="'+culang.crestAdd+'"></div>';

        t.myDiv.innerHTML = m;
        ById('bocrestslot').addEventListener('change', function(){
            if (parseIntNan(document.getElementById('bocrestslot').value)>9) document.getElementById('bocrestslot').value=1;
            Options.CrestSlot = document.getElementById('bocrestslot').value;
            saveOptions();
        }, false);


        ById('pbsendreport').addEventListener('change', function(){
            Options.crestreport = document.getElementById('pbsendreport').checked;
            saveOptions();
        }, false);
        ById('pbsendcrestreportint').addEventListener('change', function(){
            Options.CrestMsgInterval = parseIntNan(document.getElementById('pbsendcrestreportint').value);
            saveOptions();
        }, false);
        ById("pbcrest_interval").addEventListener('change', function(e){
            if (parseIntNan(e.target.value)<5) e.target.value=5;
            Options.Crestinterval = parseIntNan(e.target.value);
            saveOptions();
        },false);
        for (var i=0;i<Seed.cities.length;i++){
            if (CrestOptions.CrestCity == Seed.cities[i][0]){
                selbut=i;
                break;
            }
        }

        t.tcp = new CdispCityPicker ('crestcityselect', document.getElementById('crestcity'), true, t.clickCitySelect, selbut);

        if (CrestOptions.CrestCity == 0) {
            CrestOptions.CrestCity = t.tcp.city.id
        }
        ById('bosendreportnow').addEventListener('click', function() {
            t.sendCrestReportNow();

        }, false);

        document.getElementById('pbcrestx').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('pbcrestx').value)) document.getElementById('pbcrestx').value='' ;
        }, false);

        document.getElementById('pbcresty').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('pbcresty').value)) document.getElementById('pbcresty').value='' ;
        }, false);

        document.getElementById('R1ST').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1ST').value)) document.getElementById('R1ST').value=0 ;
        }, false);

        document.getElementById('R1MM').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1MM').value)) document.getElementById('R1MM').value=0 ;
        }, false);

        document.getElementById('R1Pike').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1Pike').value)) document.getElementById('R1Pike').value=0 ;
        }, false);

        document.getElementById('R1Scout').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1Scout').value)) document.getElementById('R1Scout').value=0 ;
        }, false);

        document.getElementById('R1Sword').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1Sword').value)) document.getElementById('R1Sword').value=0 ;
        }, false);

        document.getElementById('R1Arch').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1Arch').value)) document.getElementById('R1Arch').value=0 ;
        }, false);

        document.getElementById('R1LC').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1LC').value)) document.getElementById('R1LC').value=0 ;
        }, false);

        document.getElementById('R1HC').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1HC').value)) document.getElementById('R1HC').value=0 ;
        }, false);

        document.getElementById('R1SW').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1SW').value)) document.getElementById('R1SW').value=0 ;
        }, false);

        document.getElementById('R1Ball').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1Ball').value)) document.getElementById('R1Ball').value=0 ;
        }, false);

        document.getElementById('R1Ram').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1Ram').value)) document.getElementById('R1Ram').value=0 ;
        }, false);

        document.getElementById('R1Cat').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1Cat').value)) document.getElementById('R1Cat').value=0 ;
        }, false);

        document.getElementById('R1BT').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1BT').value)) document.getElementById('R1BT').value=0 ;
        }, false);
        
        document.getElementById('R1EX').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1EX').value)) document.getElementById('R1EX').value=0 ;
        }, false);        
        
        document.getElementById('R1SWa').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R1SWa').value)) document.getElementById('R1SWa').value=0 ;
        }, false);        
        
        document.getElementById('R2ST').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2ST').value)) document.getElementById('R2ST').value=0 ;
        }, false);

        document.getElementById('R2MM').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2MM').value)) document.getElementById('R2MM').value=0 ;
        }, false);

        document.getElementById('R2Pike').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2Pike').value)) document.getElementById('R2Pike').value=0 ;
        }, false);

        document.getElementById('R2Scout').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2Scout').value)) document.getElementById('R2Scout').value=0 ;
        }, false);

        document.getElementById('R2Sword').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2Sword').value)) document.getElementById('R2Sword').value=0 ;
        }, false);

        document.getElementById('R2Arch').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2Arch').value)) document.getElementById('R2Arch').value=0 ;
        }, false);

        document.getElementById('R2LC').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2LC').value)) document.getElementById('R2LC').value=0 ;
        }, false);

        document.getElementById('R2HC').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2HC').value)) document.getElementById('R2HC').value=0 ;
        }, false);

        document.getElementById('R2SW').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2SW').value)) document.getElementById('R2SW').value=0 ;
        }, false);

        document.getElementById('R2Ball').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2Ball').value)) document.getElementById('R2Ball').value=0 ;
        }, false);

        document.getElementById('R2Ram').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2Ram').value)) document.getElementById('R2Ram').value=0 ;
        }, false);

        document.getElementById('R2Cat').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2Cat').value)) document.getElementById('R2Cat').value=0 ;
        }, false);

        document.getElementById('R2BT').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2BT').value)) document.getElementById('R2BT').value=0 ;
        }, false);
    
        document.getElementById('R2EX').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2EX').value)) document.getElementById('R2EX').value=0 ;
        }, false);
        
        document.getElementById('R2SWa').addEventListener('keyup', function(){
            if (isNaN(document.getElementById('R2SWa').value)) document.getElementById('R2SWa').value=0 ;
        }, false);
        
        document.getElementById('crestcity').addEventListener('click', function(){CrestOptions.CrestCity = t.tcp.city.id;} , false);
        document.getElementById('Cresttoggle').addEventListener('click', function(){t.toggleCrestState(this)} , false);
        document.getElementById('pbcrestx').addEventListener('change', function(){CrestOptions.X = document.getElementById('pbcrestx').value;;} , false);
        document.getElementById('pbcresty').addEventListener('change', function(){CrestOptions.Y = document.getElementById('pbcresty').value;} , false);
        document.getElementById('R1ST').addEventListener('change', function(){CrestOptions.R1ST = document.getElementById('R1ST').value;} , false);
        document.getElementById('R1MM').addEventListener('change', function(){CrestOptions.R1MM = document.getElementById('R1MM').value;} , false);
        document.getElementById('R1Scout').addEventListener('change', function(){CrestOptions.R1Scout = document.getElementById('R1Scout').value;} , false);
        document.getElementById('R1Pike').addEventListener('change', function(){CrestOptions.R1Pike = document.getElementById('R1Pike').value;} , false);
        document.getElementById('R1Sword').addEventListener('change', function(){CrestOptions.R1Sword = document.getElementById('R1Sword').value;} , false);
        document.getElementById('R1Arch').addEventListener('change', function(){CrestOptions.R1Arch = document.getElementById('R1Arch').value;} , false);
        document.getElementById('R1LC').addEventListener('change', function(){CrestOptions.R1LC = document.getElementById('R1LC').value;} , false);
        document.getElementById('R1HC').addEventListener('change', function(){CrestOptions.R1HC = document.getElementById('R1HC').value;} , false);
        document.getElementById('R1SW').addEventListener('change', function(){CrestOptions.R1SW = document.getElementById('R1SW').value;} , false);
        document.getElementById('R1Ball').addEventListener('change', function(){CrestOptions.R1Ball = document.getElementById('R1Ball').value;} , false);
        document.getElementById('R1Ram').addEventListener('change', function(){CrestOptions.R1Ram = document.getElementById('R1Ram').value;} , false);
        document.getElementById('R1Cat').addEventListener('change', function(){CrestOptions.R1Cat = document.getElementById('R1Cat').value;} , false);
        document.getElementById('R1BT').addEventListener('change', function(){CrestOptions.R1BT = document.getElementById('R1BT').value;} , false);
        document.getElementById('R1EX').addEventListener('change', function(){CrestOptions.R1EX = document.getElementById('R1EX').value;} , false);
        document.getElementById('R1SWa').addEventListener('change', function(){CrestOptions.R1SWa = document.getElementById('R1SWa').value;} , false);

        document.getElementById('R2ST').addEventListener('change', function(){CrestOptions.R2ST = document.getElementById('R2ST').value;} , false);
        document.getElementById('R2MM').addEventListener('change', function(){CrestOptions.R2MM = document.getElementById('R2MM').value;} , false);
        document.getElementById('R2Scout').addEventListener('change', function(){CrestOptions.R2Scout = document.getElementById('R2Scout').value;} , false);
        document.getElementById('R2Pike').addEventListener('change', function(){CrestOptions.R2Pike = document.getElementById('R2Pike').value;} , false);
        document.getElementById('R2Sword').addEventListener('change', function(){CrestOptions.R2Sword = document.getElementById('R2Sword').value;} , false);
        document.getElementById('R2Arch').addEventListener('change', function(){CrestOptions.R2Arch = document.getElementById('R2Arch').value;} , false);
        document.getElementById('R2LC').addEventListener('change', function(){CrestOptions.R2LC = document.getElementById('R2LC').value;} , false);
        document.getElementById('R2HC').addEventListener('change', function(){CrestOptions.R2HC = document.getElementById('R2HC').value;} , false);
        document.getElementById('R2SW').addEventListener('change', function(){CrestOptions.R2SW = document.getElementById('R2SW').value;} , false);
        document.getElementById('R2Ball').addEventListener('change', function(){CrestOptions.R2Ball = document.getElementById('R2Ball').value;} , false);
        document.getElementById('R2Ram').addEventListener('change', function(){CrestOptions.R2Ram = document.getElementById('R2Ram').value;} , false);
        document.getElementById('R2Cat').addEventListener('change', function(){CrestOptions.R2Cat = document.getElementById('R2Cat').value;} , false);
        document.getElementById('R2BT').addEventListener('change', function(){CrestOptions.R2BT = document.getElementById('R2BT').value;} , false);
        document.getElementById('R2EX').addEventListener('change', function(){CrestOptions.R2EX = document.getElementById('R2EX').value;} , false);
        document.getElementById('R2SWa').addEventListener('change', function(){CrestOptions.R2SWa = document.getElementById('R2SWa').value;} , false);
        
        document.getElementById('CrestHelp').addEventListener('click', function(){t.helpPop();} , false);
        document.getElementById('pbSaveRouteCrest').addEventListener('click', function(){CrestOptions.active=""+culang.mainDeActivate+"";t.addCrestRoute();}, false);
        document.getElementById('showCrestTargets').addEventListener('click', function(){t.showCrestRoute();}, false);
    },


    helpPop : function (){
        var helpText = culang.crestHelp;

        var pop = new CPopup ('ArmoiriesHelp', 0, 0, 600, 420, true);
        pop.centerMe (mainPop.getMainDiv());
        pop.getMainDiv().innerHTML = helpText;
        pop.getTopDiv().innerHTML = '<div class="popupBanner"> '+culang.crestHelpPopupHead+' </div>';
        pop.show (true);
    },
    addCrestRoute : function () {
        if(CrestOptions.X == "" || CrestOptions.Y == "") {
            alert("Pas de coordonnees !");
            return;
        }
        var t = Tabs.Crest;
        var CrestLength = CrestData.length;
        CrestData[CrestLength] = new CrestFunc(CrestOptions);
        saveCrestData();
    },
    showCrestRoute : function () {
        var t = Tabs.Crest;
        var popCrestTargets = null;
        t.popCrestTargets = new CPopup('pbShowCrestTargets', 0, 0, 1100, 500, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:460px;"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowCrestTargets" id="pbCrestTargets">';
        t.popCrestTargets.getMainDiv().innerHTML = '</table></div>' + m;
        t.popCrestTargets.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.crestRoute+'</div>';
        t.paintCrestTargets();
        t._addTabHeader();
        t.popCrestTargets.show(true);

    },

    /** add header **/
    _addTabHeader : function () {
        var row = document.getElementById('pbCrestTargets').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = "<u><b>"+culang.crestRoute1+"</b></u>";
        row.insertCell(1).innerHTML = "<u><b>"+culang.crestWave+" #</b></u>";
        row.insertCell(2).innerHTML = "<img width=25 src='"+IMGmiddleSupplyTroop+"'>";
        row.insertCell(3).innerHTML = "<img width=25 src='"+IMGmiddleMilitiaman+"'>";
        row.insertCell(4).innerHTML = "<img width=25 src='"+IMGmiddleScout+"'>";
        row.insertCell(5).innerHTML = "<img width=25 src='"+IMGmiddlePikeman+"'>";
        row.insertCell(6).innerHTML = "<img width=25 src='"+IMGmiddleSwordsman+"'>";
        row.insertCell(7).innerHTML = "<img width=25 src='"+IMGmiddleArcher+"'>";
        row.insertCell(8).innerHTML = "<img width=25 src='"+IMGmiddleCavalry+"'>";
        row.insertCell(9).innerHTML = "<img width=25 src='"+IMGmiddleHeavyCavalry+"'>";
        row.insertCell(10).innerHTML = "<img width=25 src='"+IMGmiddleSupplyWagon+"'>";
        row.insertCell(11).innerHTML = "<img width=25 src='"+IMGmiddleBallista+"'>";
        row.insertCell(12).innerHTML = "<img width=25 src='"+IMGmiddleBatteringRam+"'>";
        row.insertCell(13).innerHTML = "<img width=25 src='"+IMGmiddleCatapult+"'>";
        row.insertCell(14).innerHTML = '<img width=25 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50_s34.jpg">';
        row.insertCell(15).innerHTML = '<img width=25 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50_s34.jpg">';
        row.insertCell(16).innerHTML = '<img width=25 src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50_s34.jpg">';
        row.insertCell(17).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;";
        row.insertCell(18).innerHTML = "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
    },

    /** paintCrestTargets **/
    paintCrestTargets : function () {
        t = Tabs.Crest;
        for(var i = 0; i < CrestData.length; i++) {
            t._addTabCrest(i, '<b>'+culang.crestTarget+'<b>: <a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">(' + CrestData[i].X + ',' + CrestData[i].Y+')</a>', "<b>2</b>", CrestData[i].R2ST, CrestData[i].R2MM, CrestData[i].R2Scout, CrestData[i].R2Pike, CrestData[i].R2Sword, CrestData[i].R2Arch, CrestData[i].R2LC, CrestData[i].R2HC, CrestData[i].R2SW, CrestData[i].R2Ball, CrestData[i].R2Ram, CrestData[i].R2Cat, CrestData[i].R2BT, CrestData[i].R2EX, CrestData[i].R2SWa," "," ");
            t._addTabCrest(i, CrestData[i].CrestCity, "<b>1</b>", CrestData[i].R1ST, CrestData[i].R1MM, CrestData[i].R1Scout, CrestData[i].R1Pike, CrestData[i].R1Sword, CrestData[i].R1Arch, CrestData[i].R1LC, CrestData[i].R1HC, CrestData[i].R1SW, CrestData[i].R1Ball, CrestData[i].R1Ram, CrestData[i].R1Cat, CrestData[i].R1BT, CrestData[i].R1EX, CrestData[i].R1SWa, culang.mainDelete, CrestData[i].active);
            t._addTabCrest(i, "","","","","","","","","","","","","","","","","","","");
        }
    },

    /** Add Tab Crest **/
    _addTabCrest : function (QueID, col0, col1, col2, col3, col4, col5, col6, col7, col8, col9, col10, col11, col12, col13, col14, col15, col16, col17,col18) {
        var t = Tabs.Crest;
        var row = document.getElementById('pbCrestTargets').insertRow(0);

        for (var i = 0; i <= 18; i++) {
            if (i == 17 && col17 == culang.mainDelete) {
                row.insertCell(i).innerHTML = "<a id=pbCrestDel_" + QueID + " value=" + i + "><img src='"+IMGdeleteButton+"' border=0 title='"+culang.mainDelete+"' alt='"+culang.mainDelete+"'></a>";
                document.getElementById('pbCrestDel_' + QueID).addEventListener('click', function(){t.cancelCrestTarget(QueID);}, false);
            } else if (col17 == culang.mainDelete && i == 0) {
                row.insertCell(i).innerHTML = Cities.byID[col0].name;
            } else if  (i == 18 && col17 == culang.mainDelete) {

                if (CrestData[QueID].active==""+culang.mainDeActivate+"") {
                    row.insertCell(i).innerHTML = "<a id=KsCrestAct_" + QueID + " value=" + i + ">"+culang.mainDeActivate+"</a>";
                    document.getElementById('KsCrestAct_' + QueID).addEventListener('click', function(){ CrestData[QueID].active=""+culang.mainActivate+"";saveCrestData();t.showCrestRoute();  }, false);
                } else if (CrestData[QueID].active==""+culang.mainActivate+"") {
                    row.insertCell(i).innerHTML = "<a id=KsCrestAct_" + QueID + " value=" + i + ">"+culang.mainActivate+"</a>";
                    document.getElementById('KsCrestAct_' + QueID).addEventListener('click', function(){ CrestData[QueID].active=""+culang.mainDeActivate+"";saveCrestData();t.showCrestRoute();  }, false);
                }
            }else{
                row.insertCell(i).innerHTML = eval("col" + i) + "&nbsp; &nbsp;";
            }
        }
    },

    /** Cancel Crest Target **/
    cancelCrestTarget : function (QueID) {
        var t = Tabs.Crest;
        var queueId = parseInt(QueID);
        CrestData.splice(queueId, 1);
        saveCrestData();
        t.showCrestRoute();
    },

    getRallypointLevel: function(cityId){
        var t = Tabs.Crest;
        for (var o in Seed.buildings[cityId]){
            var buildingType = parseInt(Seed.buildings[cityId][o][0]);
            var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
            if (buildingType == 12)
                t.rallypointlevel=parseInt(buildingLevel);
        }
    },

    getAtkKnight : function(cityID){
        var t = Tabs.Crest;
        t.knt = new Array();
        for (k in Seed.knights[cityID]){
            if (Seed.knights[cityID][k]["knightStatus"] == 1 && 
                    Seed.leaders[cityID]["resourcefulnessKnightId"] != Seed.knights[cityID][k]["knightId"] && 
                    Seed.leaders[cityID]["politicsKnightId"] != Seed.knights[cityID][k]["knightId"] && 
                    Seed.leaders[cityID]["combatKnightId"] != Seed.knights[cityID][k]["knightId"] && 
                    Seed.leaders[cityID]["intelligenceKnightId"] != Seed.knights[cityID][k]["knightId"]){
                t.knt.push ({
                    Name:   Seed.knights[cityID][k]["knightName"],
                    Combat:    parseInt(Seed.knights[cityID][k]["combat"]),
                    ID:            Seed.knights[cityID][k]["knightId"],
                });
            }
        }
        t.knt = t.knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
    },

    sendMarch: function(p,callback,r,retry, CrestDataNum){
        var t = Tabs.Crest;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: p,
            loading: true,
            onSuccess: function (transport) {
                try {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                        var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                        var ut = unsafeWindow.unixtime();
                        var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                        var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                        for(i = 0; i <= unitsarr.length; i++){
                            if(p["u"+i]){
                                unitsarr[i] = p["u"+i];
                            }
                        }

                        var currentcityid = p.cid;
                        unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, p.xcoord, p.ycoord, unitsarr, p.type, p.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                        
                        if (rslt.updateSeed) {
                            unsafeWindow.update_seed(rslt.updateSeed);
                        }
                        var now = new Date().getTime()/1000.0;
                        now = now.toFixed(0);
                        var rep = {
                            'city' : Cities.byID[p.cid].name,
                            'koords' : p.xcoord + "," +p.ycoord,
                            'wave' : r,
                        };
                        actionLog(""+culang.tabLabelCrest+"",culang.crestmsgOK.mreplace(rep));
                        if(r==1){
                            Options.Crest1Count++;
                            r = 2;
                            CrestData[CrestDataNum].lastRoundTwo = now;
                        } else {
                            Options.Crest2Count++;
                        }
                        saveCrestData();
                        t.timer = setTimeout (function(){callback(r,0,CrestDataNum);}, (Math.random()*10*1000)+(Options.Crestinterval*1000));
                        return;

                    } else {
                        if (rslt.user_action) {
                            actionLog(""+culang.tabLabelCrest+"","<b><font color=red>"+culang.movementCaptchaAlert+"</font></b>");
                            new CdialogCancelContinue('<SPAN class=boldRed>'+culang.crestCaptchaAlert+'</span>', null, null, mainPop.getMainDiv);
                            t.timer = setTimeout (function(){callback(r,retry,CrestDataNum);},10*60*1000);

                            return;
                        }
                        var rep = {
                            'city' : Cities.byID[p.cid].name,
                            'koords' : p.xcoord + "," +p.ycoord,
                            'wave' : r,
                            'error' : '<span style="color:red;">'+transport.responseText+'</span>',
                        };
                        actionLog(""+culang.tabLabelCrest+"",culang.crestmsgError.mreplace(rep));
                        t.timer = setTimeout (function(){callback(r,retry,CrestDataNum);}, Options.Crestinterval*1000);
                        return;
                    }
                } catch(err) {
                        var rep = {
                            'city' : Cities.byID[p.cid].name,
                            'koords' : p.xcoord + "," +p.ycoord,
                            'wave' : r,
                        };
                        actionLog(""+culang.tabLabelCrest+"",culang.crestmsgCodeError.mreplace(rep));
                    t.timer = setTimeout (function(){callback(r,retry,CrestDataNum);}, 1000);
                    return;
                }
            },
            onFailure: function () {
                        var rep = {
                            'city' : Cities.byID[p.cid].name,
                            'koords' : p.xcoord + "," +p.ycoord,
                            'wave' : r,
                        };
                        actionLog(""+culang.tabLabelCrest+"",culang.crestmsgFatalError.mreplace(rep));
                setTimeout (function(){callback(r,retry,CrestDataNum);}, Options.Crestinterval*1000);
                return;
            }
        });
    },

    abandonWilderness: function(tid,x,y,cid,callback,retry, CrestDataNum){
        var t = Tabs.Crest;
        if (!Options.crestRunning) return;

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        var cityID = cid;
        var tileid = tid;
        params.tid=tid;
        params.cid=cid;
        params.x=x;
        params.y=y;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/abandonWilderness.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess:function(transport){
                var rslt=eval("("+transport.responseText+")");
                if (rslt.ok) {
                    t.error_code = 0;
                    if (rslt.returningMarches) {
                        var cities = Object.keys(rslt.returningMarches);
                        for (var i = 0; i < cities.length; i++) {
                            for (var j = 0; j < rslt.returningMarches[cities[i]].length; j++) {
                                var cid = cities[i].split("c")[1];
                                var mid = rslt.returningMarches[cities[i]][j];
                                var march = Seed.queue_atkp["city" + cid]["m" + mid];
                                if (march) {
                                    var marchtime = Math.abs(parseInt(march.destinationUnixTime) - parseInt(march.marchUnixTime));
                                    var ut = unsafeWindow.unixtime();
                                    Seed.queue_atkp["city" + cid]["m" + mid].destinationUnixTime = ut;
                                    Seed.queue_atkp["city" + cid]["m" + mid].marchUnixTime = ut - marchtime;
                                    Seed.queue_atkp["city" + cid]["m" + mid].returnUnixTime = ut + marchtime;
                                    Seed.queue_atkp["city" + cid]["m" + mid].marchStatus = 8
                                }
                            }
                        }
                    }
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                    if (Object.keys(Seed.wilderness["city" + cityID]).length == 1) {
                        Seed.wilderness["city" + cityID] = []
                    } else    {
                        delete Seed.wilderness["city"+cityID]["t"+tileid];
                    }
                } else {
                    if (rslt.error_code != 401) {
                        t.error_code = rslt.error_code;
                    }
                }
            },
            onFailure: function () {}
        });
    },

    Rounds : function (r, retry, CrestDataNum) {
        var t = Tabs.Crest;
        clearTimeout(t.timer);
        if (!Options.crestRunning) return;

        if (CrestData.length == 0)
            return;

        if (CrestDataNum >= CrestData.length)
            CrestDataNum = 0;

        if (CrestData[CrestDataNum].active==""+culang.mainActivate+"") {
            t.timer =setTimeout(function() { t.Rounds(1,0,parseInt(CrestDataNum+1)); },1000);
            return;
        }

        cityID = 'city' + CrestData[CrestDataNum].CrestCity;
        retry++;

        for (var k in Seed.wilderness[cityID] ){
            if (Seed.wilderness[cityID][k]['xCoord']==CrestData[CrestDataNum].X && Seed.wilderness[cityID][k]['yCoord']==CrestData[CrestDataNum].Y && t.error_code!=401) {
                t.abandonWilderness(Seed.wilderness[cityID][k]['tileId'],Seed.wilderness[cityID][k]['xCoord'],Seed.wilderness[cityID][k]['yCoord'],CrestData[CrestDataNum].CrestCity,t.Rounds,retry,CrestDataNum);
            }
        }
        
        if (parseInt(Seed.units[cityID]['unt1']) < CrestData[CrestDataNum].R1ST || 
                parseInt(Seed.units[cityID]['unt2']) < CrestData[CrestDataNum].R1MM || 
                parseInt(Seed.units[cityID]['unt3']) < CrestData[CrestDataNum].R1Scout || 
                parseInt(Seed.units[cityID]['unt4']) < CrestData[CrestDataNum].R1Pike || 
                parseInt(Seed.units[cityID]['unt5']) < CrestData[CrestDataNum].R1Sword || 
                parseInt(Seed.units[cityID]['unt6']) < CrestData[CrestDataNum].R1Arch || 
                parseInt(Seed.units[cityID]['unt7']) < CrestData[CrestDataNum].R1LC || 
                parseInt(Seed.units[cityID]['unt8']) < CrestData[CrestDataNum].R1HC || 
                parseInt(Seed.units[cityID]['unt9']) < CrestData[CrestDataNum].R1SW || 
                parseInt(Seed.units[cityID]['unt10']) < CrestData[CrestDataNum].R1Ball || 
                parseInt(Seed.units[cityID]['unt11']) < CrestData[CrestDataNum].R1Ram || 
                parseInt(Seed.units[cityID]['unt12']) < CrestData[CrestDataNum].R1Cat || 
                parseInt(Seed.units[cityID]['unt13']) < CrestData[CrestDataNum].R1BT || 
                parseInt(Seed.units[cityID]['unt14']) < CrestData[CrestDataNum].R1EX || 
                parseInt(Seed.units[cityID]['unt15']) < CrestData[CrestDataNum].R1SWa || 
                parseInt(Seed.units[cityID]['unt1']) < CrestData[CrestDataNum].R2ST || 
                parseInt(Seed.units[cityID]['unt2']) < CrestData[CrestDataNum].R2MM || 
                parseInt(Seed.units[cityID]['unt3']) < CrestData[CrestDataNum].R2Scout || 
                parseInt(Seed.units[cityID]['unt4']) < CrestData[CrestDataNum].R2Pike || 
                parseInt(Seed.units[cityID]['unt5']) < CrestData[CrestDataNum].R2Sword || 
                parseInt(Seed.units[cityID]['unt6']) < CrestData[CrestDataNum].R2Arch || 
                parseInt(Seed.units[cityID]['unt7']) < CrestData[CrestDataNum].R2LC || 
                parseInt(Seed.units[cityID]['unt8']) < CrestData[CrestDataNum].R2HC || 
                parseInt(Seed.units[cityID]['unt9']) < CrestData[CrestDataNum].R2SW || 
                parseInt(Seed.units[cityID]['unt10']) < CrestData[CrestDataNum].R2Ball || 
                parseInt(Seed.units[cityID]['unt11']) < CrestData[CrestDataNum].R2Ram || 
                parseInt(Seed.units[cityID]['unt12']) < CrestData[CrestDataNum].R2Cat ||
                parseInt(Seed.units[cityID]['unt13']) < CrestData[CrestDataNum].R2BT ||
                parseInt(Seed.units[cityID]['unt14']) < CrestData[CrestDataNum].R2EX ||
                parseInt(Seed.units[cityID]['unt15']) < CrestData[CrestDataNum].R2SWa) {
            if (CrestData.length == 1) {
                t.timer =setTimeout(function(){ t.Rounds(r,retry,CrestDataNum);},Options.Crestinterval*1000);
                return;
            } else
                t.timer =setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
            return;
        }

        t.getAtkKnight(cityID);
        slots=0;

        for (z in Seed.queue_atkp[cityID]) {
            slots++;
        }
        if  (Seed.queue_atkp[cityID].toSource() == "[]")
            slots=0;

        slots=parseInt(slots)+parseInt(Options.CrestSlot); // protection slots
        t.getRallypointLevel(cityID);
        var add = 0;
        if (Seed.cityData.city[CrestData[CrestDataNum].CrestCity].isPrestigeCity) {
            add = 3;
        }
        switch (t.rallypointlevel) {
            case 12:
                t.rallypointlevel = t.rallypointlevel - 1;
            default:
                t.rallypointlevel = t.rallypointlevel + add;
                if (t.rallypointlevel <= slots) {
                    if (CrestData.length == 1) {
                        t.timer = setTimeout(function(){ t.Rounds(r,retry,CrestDataNum);},Options.Crestinterval*1000);
                    } else {
                        t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
                    }
                    return;
                    break;
                }
        }
        
        if  (t.knt.toSource() == "[]") {
            t.timer = setTimeout(function(){ t.Rounds(1,retry,parseInt(CrestDataNum)+1);},Options.Crestinterval*1000);
            return;
        }
        var kid = t.knt[0].ID;
        if (CrestData[CrestDataNum].R1ST == 0 && 
                CrestData[CrestDataNum].R1MM == 0 && 
                CrestData[CrestDataNum].R1Scout == 0 && 
                CrestData[CrestDataNum].R1Pike == 0 && 
                CrestData[CrestDataNum].R1Sword == 0 && 
                CrestData[CrestDataNum].R1Arch == 0 && 
                CrestData[CrestDataNum].R1LC == 0 && 
                CrestData[CrestDataNum].R1HC == 0 && 
                CrestData[CrestDataNum].R1SW == 0 && 
                CrestData[CrestDataNum].R1Ball == 0 && 
                CrestData[CrestDataNum].R1Ram == 0 &&
                CrestData[CrestDataNum].R1Cat == 0 &&
                CrestData[CrestDataNum].R1BT == 0 &&
                CrestData[CrestDataNum].R1EX == 0 &&
                CrestData[CrestDataNum].R1SWa == 0) {
            r=2;
        }else {
            var now = new Date().getTime()/1000.0;
            now = now.toFixed(0);
            if (now > (parseInt(CrestData[CrestDataNum].lastRoundTwo) + 300)) { // 3 minutes entre les premi?res vagues 
                r=1;
            }
        }

        var troopCount = 0;
        switch(r) {
            case 1:
                if ((t.rallypointlevel-slots) < 2) {
                    t.timer =setTimeout(function(){ t.Rounds(1,retry,(parseInt(CrestDataNum)+1));},Options.Crestinterval*1000);
                    return;
                }
                var params         =     unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                params.cid        =     CrestData[CrestDataNum].CrestCity;
                params.type        =    4;
                params.kid        =     kid;
                params.xcoord     =     CrestData[CrestDataNum].X;
                params.ycoord     =     CrestData[CrestDataNum].Y;
                params.u1         =     CrestData[CrestDataNum].R1ST; troopCount += parseInt(params.u1);
                params.u2         =     CrestData[CrestDataNum].R1MM; troopCount += parseInt(params.u2);
                params.u3         =     CrestData[CrestDataNum].R1Scout; troopCount += parseInt(params.u3);
                params.u4         =     CrestData[CrestDataNum].R1Pike; troopCount += parseInt(params.u4);
                params.u5         =     CrestData[CrestDataNum].R1Sword; troopCount += parseInt(params.u5);
                params.u6         =     CrestData[CrestDataNum].R1Arch; troopCount += parseInt(params.u6);
                params.u7         =     CrestData[CrestDataNum].R1LC; troopCount += parseInt(params.u7);
                params.u8         =     CrestData[CrestDataNum].R1HC; troopCount += parseInt(params.u8);
                params.u9         =     CrestData[CrestDataNum].R1SW; troopCount += parseInt(params.u9);
                params.u10         =     CrestData[CrestDataNum].R1Ball; troopCount += parseInt(params.u10);
                params.u11         =     CrestData[CrestDataNum].R1Ram; troopCount += parseInt(params.u11);
                params.u12         =     CrestData[CrestDataNum].R1Cat; troopCount += parseInt(params.u12);
                params.u13         =     CrestData[CrestDataNum].R1BT; troopCount += parseInt(params.u13);
                params.u14         =     CrestData[CrestDataNum].R1EX; troopCount += parseInt(params.u14);
                params.u15         =     CrestData[CrestDataNum].R1SWa; troopCount += parseInt(params.u15);
                if (troopCount > 0){
                    t.sendMarch(params,t.Rounds,r,retry, CrestDataNum);
                }else{
                    //Log
                    var rep = {
                        'city' : Cities.byID[params.cid].name,
                        'koords' : params.xcoord + "," +params.ycoord,
                        'wave' : r,
                        'error' : '<span style="color:red;">{no troops}</span>',
                    };
                    actionLog(culang.tabLabelCrest,culang.crestmsgError.mreplace(rep));
                }
                break;
            default:
                var params         =     unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                params.cid        =     CrestData[CrestDataNum].CrestCity;
                params.type        =     4;
                params.kid        =     kid;
                params.xcoord     =     CrestData[CrestDataNum].X;
                params.ycoord     =     CrestData[CrestDataNum].Y;
                params.u1         =     CrestData[CrestDataNum].R2ST; troopCount += parseInt(params.u1);
                params.u2         =     CrestData[CrestDataNum].R2MM; troopCount += parseInt(params.u2);
                params.u3         =     CrestData[CrestDataNum].R2Scout; troopCount += parseInt(params.u3);
                params.u4         =     CrestData[CrestDataNum].R2Pike; troopCount += parseInt(params.u4);
                params.u5         =     CrestData[CrestDataNum].R2Sword; troopCount += parseInt(params.u5);
                params.u6         =     CrestData[CrestDataNum].R2Arch; troopCount += parseInt(params.u6);
                params.u7         =     CrestData[CrestDataNum].R2LC; troopCount += parseInt(params.u7);
                params.u8         =     CrestData[CrestDataNum].R2HC; troopCount += parseInt(params.u8);
                params.u9         =     CrestData[CrestDataNum].R2SW; troopCount += parseInt(params.u9);
                params.u10         =     CrestData[CrestDataNum].R2Ball; troopCount += parseInt(params.u10);
                params.u11         =     CrestData[CrestDataNum].R2Ram; troopCount += parseInt(params.u11);
                params.u12         =     CrestData[CrestDataNum].R2Cat; troopCount += parseInt(params.u12);
                params.u13         =     CrestData[CrestDataNum].R2BT; troopCount += parseInt(params.u13);
                params.u14         =     CrestData[CrestDataNum].R2EX; troopCount += parseInt(params.u14);
                params.u15         =     CrestData[CrestDataNum].R2SWa; troopCount += parseInt(params.u15);
                if (troopCount > 0){
                    t.sendMarch(params,t.Rounds,r,retry, CrestDataNum);
                }else{
                    //Log
                    var rep = {
                        'city' : Cities.byID[params.cid].name,
                        'koords' : params.xcoord + "," +params.ycoord,
                        'wave' : r,
                        'error' : '<span style="color:red;">{no troops}</span>',
                    };
                    actionLog(culang.tabLabelCrest,culang.crestmsgError.mreplace(rep));
                }
                break;
        }

    },

    toggleCrestState: function(obj) {
        var t = Tabs.Crest;
        obj = ById('Cresttoggle');
        if (Options.crestRunning == true) {
            Options.crestRunning = false;
            if (obj) obj.value = culang.tabLabelCrest+" = "+culang.buttonOFF;
            saveOptions();
        } else {
            Options.crestRunning = true;
            if (obj) obj.value = culang.tabLabelCrest+" = "+culang.buttonON;
            Options.Creststatus={1101:0,1102:0,1103:0,1104:0,1105:0,1106:0,1107:0,1108:0,1109:0,1110:0,1111:0,1112:0,1113:0,1114:0,1115:0,9:0,36:0,37:0,38:0,55:0,57:0,261:0,262:0,271:0,272:0,351:0,361:0,362:0,911:0,3000:0,3001:0,3002:0,3003:0,3007:0,3008:0,3009:0,3011:0,931:0,932:0,285:0,};
            for (crest in Options.Creststatus) {
                owned = Seed.items['i'+crest];
                if (owned == undefined) {
                    owned=0;
                }
                Options.Creststatus[crest] = owned;
                Options.Crest1Count = 0;
                Options.Crest2Count = 0;
            }
            var now = new Date().getTime()/1000.0;
            now = now.toFixed(0);
            Options.LastCrestReport = now;
            saveOptions();
            t.timer =setTimeout(function(){ t.Rounds(1,0,0);}, 1000);
        }
    },
    sendCrestReportNow: function(){
        var t = Tabs.Crest;
        var now = new Date().getTime()/1000.0;
        now = now.toFixed(0);
        var total = 0;
        var wildtype = '';

        var message = ''+culang.crestReportHead+' %0A';
        message += '%0A '+culang.crestReportCrestFound+' %0A';

        for (crest in Options.Creststatus) {
            owned = Seed.items['i'+crest];
            if (owned == undefined)
                owned =    0;
            if ((owned - Options.Creststatus[crest]) > 0)
                message    +=     '<DIV><B>' + unsafeWindow.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A </b></div>';
            total += (owned - Options.Creststatus[crest]);
            Options.Creststatus[crest] = owned;

        }
        message += '%0A '+culang.mainTime+': ' + timestr(now-Options.LastCrestReport) + '%0A'
        message += '%0A  '+culang.crestReportCrestTotal+'  '+ total +' '+culang.crestReportCrestTotal2+'%0A';
        message += '%0A '+culang.crestReportFirstWave+' '+ Options.Crest1Count +' '+culang.crestReportFirstWave2+' %0A';
        message += ''+culang.crestReportSecondWave+' '+ Options.Crest2Count +' '+culang.crestReportSecondWave2+' %0A';

        Options.Crest1Count = 0;
        Options.Crest2Count = 0;
        Options.Crest3Count = 0;
        Options.Crest4Count = 0;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.emailTo = Seed.player['name'];
        params.subject = culang.crestReport;
        params.message = message;
        params.requestType = "COMPOSED_MAIL";
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (message) {
                var rslt = eval("(" + message.responseText + ")");
                if (rslt.ok) {
                    Options.LastCrestReport = now;
                } else {
                }
            },
            onFailure: function () {
            },
        });
        saveOptions();
    },
    sendCrestReport: function(){
        if(!Options.crestreport || !CrestOptions.Running)
            return;

        var t = Tabs.Crest;
        var now = new Date().getTime()/1000.0;
        now = now.toFixed(0);

        if (now < (parseInt(Options.LastCrestReport)+(Options.CrestMsgInterval*60*60)))
            return;

        var total = 0;
        var wildtype =     '';

        var message = ''+culang.crestReportHead+' %0A';
        message += '%0A '+culang.crestReportCrestFound+' %0A';

        for (crest in Options.Creststatus) {
            owned = Seed.items['i'+crest];
            if (owned == undefined)
                owned =    0;
            if ((owned - Options.Creststatus[crest]) > 0)
                message    +=     '<DIV><B>' + unsafeWindow.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A </b></div>';
            else
                message    +=     unsafeWindow.itemlist['i'+crest]['name'] +': '+ (owned - Options.Creststatus[crest]) +'%0A';

            total += (owned - Options.Creststatus[crest]);
            Options.Creststatus[crest] = owned;
        }

        message += '%0A '+culang.crestReportCrestTotal+' '+ total +' '+culang.crestReportCrestTotal2+' %0A';
        message += '%0A '+culang.crestReportFirstWave+' '+ Options.Crest1Count +' '+culang.crestReportFirstWave2+' %0A';
        message += ''+culang.crestReportSecondWave+' '+ Options.Crest2Count +' '+culang.crestReportSecondWave2+' %0A';

        Options.Crest1Count = 0;
        Options.Crest2Count = 0;

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.emailTo = Seed.player['name'];
        params.subject = culang.crestReport;
        params.message = message;
        params.requestType = "COMPOSED_MAIL";

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (message) {
                var rslt = eval("(" + message.responseText + ")");
                if (rslt.ok) {
                    Options.LastCrestReport = now;
                }
            },
            onFailure: function () {
            },
        });

        saveOptions();
    },


    hide : function (){
        var t = Tabs.Crest;
    },

    show : function (){
    },
};
//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/Transport.js">
/************************************************************************************
 *                        KOC POWER - TABS TRANSPORT                                    *
 ************************************************************************************/
Tabs.Transport = {
    tabOrder: TabOptions.toTransport,
    tabLabel: culang.mainTransport,
    cont : null,
    displayTimer : null,
    state : null,
    curTabBut : null,
    curTabName : null,
    sourceCity : {},
    destinationCity : {},
    rows : [],
    timer: null,
    timer2: null,
    traderState: [],
    reapproState: [],
    lTR: [],
    tradeRoutes: [],
    checkdotradetimeout: null,
    checkdoreapprotimeout: null,
    count:0,
    check:false,
    show : function (){
        var t = Tabs.Transport;
        if (document.getElementById ('maparea_map').style.display!="none") {
            if (t.destinationCityx) {
                t.destinationCityx.value = document.getElementById ('mapXCoor').value;
                t.destinationCityy.value = document.getElementById ('mapYCoor').value;
            }
        }
        if (t.curTabBut) {
            var but=t.curTabBut;
            t.show2();
        }
    },
    hide : function (){
        var t = Tabs.Transport;
        clearTimeout (t.displayTimer);
        clearTimeout (t.timer);
    },

    init : function (div){
        var t = Tabs.Transport;
        unsafeWindow.Ksestimeres = t.estimerRes;
        t.traderState = {running: false,};
        t.reapproState = {running: false,city:-1,unit:9,mini:1000};
        t.readTraderState();
        t.readReapproState();
        t.readTradeRoutes();
        t.e_tradeRoutes();

        window.addEventListener('unload', t.onUnload, false);
        t.cont = div;
        t.cont.innerHTML = '<TABLE class=pdxTab align=center><TR><TD><INPUT class=ksMSubtab ID=BoTrpSubM type=submit value="'+culang.transportTabLabel+'"></td>\
             <TD><INPUT class=ksMSubtab ID=BoTrpSubA type=submit  value="'+culang.transportAutoTabLabel+'"></td><TD><INPUT class=ksMSubtab ID=BoTrpSubR type=submit  value="'+culang.transportSupplyTabLabel+'"></td></tr></table>\
         <DIV id="BoTrpOutput" style="margin-top:5px; background-color:white; max-height:'+(Options.HauteurBoite-65)+'px;overflow-y:auto"></div>';
        t.TransportDiv = ById('BoTrpOutput');
        ById('BoTrpSubA').addEventListener('click', e_butSubtab, false);
        ById('BoTrpSubM').addEventListener('click', e_butSubtab, false);
        ById('BoTrpSubR').addEventListener('click', e_butSubtab, false);

        changeSubtab (ById('BoTrpSubM'));

        function e_butSubtab (evt){
            changeSubtab (evt.target);
        }

        function changeSubtab (but){
            if (but == t.curTabBut)
                return;
            if (t.curTabBut){
                t.curTabBut.className='ksMSubtab';
                t.curTabBut.disabled=false;
            }
            t.curTabBut = but;
            but.className='ksMSubtab ksMSubtabSel';
            but.disabled=true;
            t.curTabName = but.id.substr(8);
            t.show2();
        }
        var final = 0;
        if (t.reapproState.city>=0) {
            for(var i=0; i<Cities.numCities; i++) {
                var x2 = parseInt(Cities.cities[i].x);
                var x1 = parseInt(Cities.cities[t.reapproState.city].x);
                var y2 = parseInt(Cities.cities[i].y);
                var y1 = parseInt(Cities.cities[t.reapproState.city].y);
                var dist = distance (x1, y1, x2, y2);
                var m = estETA(dist,t.reapproState.unit,Cities.cities[t.reapproState.city].id,1);
                if (m.friendETA>final)
                    final=m.friendETA;
            }
            //Options.reapprointerval = parseInt(final/60*2+10);
        }
    },
    show2 : function (){
        var t = Tabs.Transport
        t.state = null;
        clearTimeout (t.displayTimer);
        clearTimeout (t.timer);
        if (t.curTabName == 'M')
            t.showManuel();
        else  if (t.curTabName == 'R')
            t.showReappro();
        else {
            t.showAuto();
            t.showTimer();
        }
        if (t.reapproState.running == true) {
            t.checkdoreapprotimeout = setTimeout(t.actionreappro, 10000);
        }
        
    },
    showTimer: function() {
        var t = Tabs.Transport;
        t.updateTroops();
        t.updateResources();
        t.timer = setTimeout (t.showTimer, 1000);
    },
    showReappro: function () {
        var t = Tabs.Transport;
        var m = '<DIV id=pbSupplyTab class=pdxStat>'+culang.transportSupplyHead+' - <input type=button value="?" id=boaideappro class=buttonHelp></div><TABLE id=pbtraderfunctions width=100% height=0% class=pdxTab><TR align="center"><TD><span title="+ 10 '+culang.mainMinutes+'"><b>'+culang.mainIntervall+'</b>: <INPUT id=pbreapprointerval type=text size=2 value="'+Options.reapprointerval+'"\> '+culang.mainMinutes+'</td><td><input type=button value="'+culang.buttonSave+'" id="boReappro"></td>';
        if (t.reapproState.running == false) {
            m += '<TD><INPUT id=boReapproState type=submit value="'+culang.shrsupply+' = '+culang.buttonOFF+' "></td>';
        } else {
            m += '<TD><INPUT id=boReapproState type=submit value="'+culang.shrsupply+' = '+culang.buttonON+' "></td>';
        }
        m += '</tr></table>';
        m += '<DIV id=pbReapproDivDRoute class=pdxStat>'+culang.transportSupplyHeadSettings+'</div>';
        m += '<TABLE id=pbaddReapproroute width=95% height=0% class=pdxTab><TR align="left">';
        m += '<TR align="left"><TD colspan=2><b>'+culang.mainCastle+'</b>:</td> <TD colspan=3><DIV style="margin-bottom:10px;"><span id=borescity></span></div></td><td colspan=4><b>'+culang.mainTroops+'</b>: <select id="KsApproUnit"><option value=9>'+culang.shrsupplywagon+'</option><option value=7>'+culang.shrcavalry+'</option><option value=8>'+culang.heavycavalry+'</option></select>&nbsp; '+culang.shortMin+': <input type=text size=5 value="0" id=KsApproMin></td></tr>';

        var Types = ['gold','food','wood','stone','iron','aetherstone'];

        m += '<TR align="left"><td colspan=2></td>';
        for (var y=0; y< Seed.cities.length;y++)
            m += '<td><b><u>'+Seed.cities[y][1]+'</u></b></td>';
        for (var i=0;i<=5;i++) {
            m += '</tr><tr><td align=center valign=middle rowspan=2><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/'+Types[i]+'_30.png"></td><td></td>';
            for (var y=0; y< Seed.cities.length;y++)
                m += '<td><span id="ReappRec_'+y+'_'+i+'"></span></td>';
            m += '</tr><tr><td>'+culang.transportSupplyKeep+'</td>';
            for (var y=0; y< Seed.cities.length;y++)
                m += '<td><input id="ReappRes_'+y+'_'+i+'" type=text size=10 maxlength=12 value=0></td>';
            m +='</tr>';
        }
        m += '</table><div style="font-size:10px; color:#555; text-align:center;"> '+culang.transportValue+' </div>';
        t.TransportDiv.innerHTML = m;
        if (t.reapproState.city==undefined ||t.reapproState.city==-1) {

            t.reapproState.city=0;
        }
        ById('boaideappro').addEventListener('click', function(){
            window.open(homePage+" ");
        } , false);
        t.reacp = new CdispCityPicker ('botrader', ById('borescity'), true, t.updateResources2, t.reapproState.city);
        ById('KsApproMin').addEventListener('change', function(){
            t.reapproState.mini = ById('KsApproMin').value;
            t.saveReappro();
        }, false);
        ById('boReapproState').addEventListener('click', function(){t.toggleReapproState(this);}, false);
        ById('boReappro').addEventListener('click', function(){t.saveReappro();}, false);

        ById('pbreapprointerval').addEventListener('change', function(){
            if (isNaN(ById('pbreapprointerval').value)) { 
                ById('pbreapprointerval').value=60;
            }
            Options.reapprointerval = parseInt(ById('pbreapprointerval').value);
            saveOptions();
        }, false);

        //ById('KsRecupReappro').addEventListener('click', function(){t.RecupReappro();}, false);
        ById('KsApproUnit').value = t.reapproState.unit;
        ById('KsApproMin').value = parseIntNan(t.reapproState.mini);
        ById('KsApproUnit').addEventListener('change', function(){
            t.reapproState.unit = ById('KsApproUnit').value;
            t.saveReappro();

        }, false);

        t.updateResources2();
    },
    RecupReappro:function() {
        var t = Tabs.Transport;
        var r = t.tradeRoutes;
        for (var y=0; y< Seed.cities.length;y++) {
            for (var i=0;i<(r.length);i++) {
                if (parseInt(Seed.cities[y][0]) == r[i].city) {
                    ById('ReappRes_'+y+'_0').value=r[i].target_Gold;
                    ById('ReappRes_'+y+'_1').value=r[i].target_Food;
                    ById('ReappRes_'+y+'_2').value=r[i].target_Wood;
                    ById('ReappRes_'+y+'_3').value=r[i].target_Stone;
                    ById('ReappRes_'+y+'_4').value=r[i].target_Ore;
                    ById('ReappRes_'+y+'_5').value=r[i].target_Astone;

                }
            }
        }
        t.saveReappro();
    },
    saveReapproState: function(){
        var t = Tabs.Transport;
        var serverID = getServerId();
        GM_setValue('reapproState_' + serverID, JSON2.stringify(t.reapproState));
    },
    saveReappro:function() {
        var t = Tabs.Transport;
        for (var y=0; y< Seed.cities.length;y++) {
            t.reapproState['ReappRes_'+y+'_0'] = parseIntNan(ById('ReappRes_'+y+'_0').value);
            for (var i=1;i<=5;i++) {
                t.reapproState['ReappRes_'+y+'_'+i] = parseIntNan(ById('ReappRes_'+y+'_'+i).value);
            }
        }
        t.saveReapproState();
    },
    readReapproState: function(){
        var t = Tabs.Transport;
        var serverID = getServerId();
        s = GM_getValue('reapproState_' + serverID);
        if (s != null) {
            state = JSON2.parse(s);
            for (k in state)
                t.reapproState[k] = state[k];
        }
    },
    toggleReapproState: function(obj){
        var t = Tabs.Transport;
        obj = ById('boReapproState');
        if (t.reapproState.running == true) {
            t.reapproState.running = false;
            if (obj)  obj.value = ""+culang.shrsupply+" = "+culang.buttonOFF;
            clearTimeout(t.checkdoreapprotimeout);
        }
        else {
            t.reapproState.running = true;
            if (obj) obj.value = ""+culang.shrsupply+" = "+culang.buttonON;
            t.actionreappro();
        }
    },
    retry:0,
    nbcity:-1,
    actionreappro:function() {
        var t = Tabs.Transport;
        t.nbcity++;
        if (t.reapproState.running == false) {
            clearTimeout(t.checkdoreapprotimeout);
            return;
        }
        if (t.nbcity==t.reapproState.city)
            t.nbcity++;
        var tempsprochainevisite = 10000;
        if ((Seed.cities.length-1)<t.nbcity) {
            tempsprochainevisite = Options.reapprointerval*60*1000;
            t.nbcity=-1;
        } else {
            var besoin=[0,0,0,0,0,0];
            var stock=[0,0,0,0,0,0];
            qtemin = parseIntNan(t.reapproState['ReappRes_'+t.nbcity+'_0']);
            qtest = parseIntNan(Seed.citystats["city" + Seed.cities[t.nbcity][0]]['gold'][0]);
            if (qtest<qtemin)
                besoin[0] = parseInt(qtemin - qtest);
            stock[0] = parseIntNan(Seed.citystats["city" + Seed.cities[t.reapproState.city][0]]['gold'][0]);
            for (var i=1;i<=5;i++) {
                qtemin = parseIntNan(t.reapproState['ReappRes_'+t.nbcity+'_'+i]);
                if(i==5) {
                    qtest = parseInt(Seed.resources["city" + Seed.cities[t.nbcity][0]]['rec'+i][0]);
                    qtstock = parseInt(Seed.resources["city" + Seed.cities[t.reapproState.city][0]]['rec'+i][0]);
                }else {
                    qtest = parseInt(Seed.resources["city" + Seed.cities[t.nbcity][0]]['rec'+i][0]/3600);
                    qtstock= parseInt(Seed.resources["city" + Seed.cities[t.reapproState.city][0]]['rec'+i][0]/3600);
                }
                if (qtest<qtemin)
                    besoin[i] = parseInt(qtemin - qtest);
                stock[i] = qtstock;
            }
            var RInfo = getRallypointInfo(Cities.cities[t.reapproState.city].id);
            if(RInfo.usedSlots >= RInfo.maxMarches){
                actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+" <font color=red>"+culang.transportSupplyLogFullRP+"</font>");
                return;
            }
            if (besoin[0]>0 || besoin[1]>0|| besoin[2]>0 || besoin[3]>0 || besoin[4]>0 || besoin[5]>0) {
                //actionLog(""+culang.mainSupply+"","Transport von: "+Cities.cities[t.reapproState.city].name+" nach: "+Cities.cities[t.nbcity].name+" : pierre:" + besoin[3] +"<"+stock[3]+" && mine: "+besoin[4]+"<"+stock[4]+"");
                if (besoin[0]<=stock[0] && besoin[1]<=stock[1] && besoin[2]<=stock[2] && besoin[3]<=stock[3] && besoin[4]<=stock[4] && besoin[5]<=stock[5]) {
                    var unit = 'unt' + t.reapproState.unit;
                    Troops = parseInt(Seed.units['city' + Seed.cities[t.reapproState.city][0]][unit]);
                    var untid=t.reapproState.unit;
                    
                    var techLoadBoost = parseInt(Seed.tech.tch10)*0.1;
                    var loadEffectBoost = 0;
                    if (Seed.playerEffects.loadExpire > uW.unixtime()) loadEffectBoost = 25;
                    var loadBoost = uW.cm.ThroneController.effectBonus(6) + loadEffectBoost;
                    if (uW.cm.unitFrontendType[untid]=="siege") {
                        if (untid != 9) loadBoost += uW.cm.ThroneController.effectBonus(59);
                    } else {
                        if (uW.cm.unitFrontendType[untid]=="horsed") {
                            loadBoost += uW.cm.ThroneController.effectBonus(48);
                        }
                    }
                    if (loadBoost > 500) {
                        loadBoost = 5;
                    } else {
                        loadBoost = loadBoost * 0.01;
                    }
                    var LoadUnit = parseInt(parseInt(uW.unitstats[unit][5]) * (1 + loadBoost + techLoadBoost));
                    
                    TroopsNeeded = (besoin[0] + besoin[1] + besoin[2] + besoin[3] + besoin[4] + (besoin[5]*5))  / LoadUnit;
                    TroopsNeeded = TroopsNeeded.toFixed(0);
                    if (TroopsNeeded < ((besoin[0] + besoin[1] + besoin[2] + besoin[3] + besoin[4] + (besoin[5]*5))  / LoadUnit )) TroopsNeeded++;
                    var RInfo = getRallypointInfo(Seed.cities[t.reapproState.city][0]);
                    if (parseInt(TroopsNeeded) > RInfo.maxMarchSize){
                        TroopsNeeded = RInfo.maxMarchSize;
                        var lemax=LoadUnit*TroopsNeeded;
                        var totalb=lemax;
                        for (var i=1;i<=5;i++) {
                            if (besoin[i]>=totalb)
                                besoin[i]=totalb;
                            totalb=totalb-besoin[i];
                        }
                    }
                    if (parseIntNan(TroopsNeeded)<=parseIntNan(Troops) && parseIntNan(TroopsNeeded)>=parseIntNan(t.reapproState.mini)) {
                        var city = Seed.cities[t.reapproState.city][0];
                        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                        params.gold =besoin[0];
                        params.r1 =besoin[1];
                        params.r2 =besoin[2];
                        params.r3 =besoin[3];
                        params.r4 =besoin[4];
                        params.r5 =besoin[5];
                        params.kid = 0;
                        params.type = "1";
                        params.cid=city;
                        switch (unit){
                            case 'unt1': params.u1 = TroopsNeeded;break;
                            case 'unt2': params.u2 = TroopsNeeded;break;
                            case 'unt3': params.u3 = TroopsNeeded;break;
                            case 'unt4': params.u4 = TroopsNeeded;break;
                            case 'unt5': params.u5 = TroopsNeeded;break;
                            case 'unt6': params.u6 = TroopsNeeded;break;
                            case 'unt7': params.u7 = TroopsNeeded;break;
                            case 'unt8': params.u8 = TroopsNeeded;break;
                            case 'unt9': params.u9 = TroopsNeeded;break;
                            case 'unt10': params.u10 = TroopsNeeded;break;
                            case 'unt11': params.u11 = TroopsNeeded;break;
                            case 'unt12': params.u12 = TroopsNeeded;break;
                            case 'unt13': params.u13 = TroopsNeeded;break;
                            case 'unt14': params.u14 = TroopsNeeded;break;
                            case 'unt15': params.u15 = TroopsNeeded;break;
                        }
                        params.xcoord = Seed.cities[t.nbcity][2];
                        params.ycoord = Seed.cities[t.nbcity][3];

                        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                            method: "post",
                            parameters: params,
                            loading: true,
                            onSuccess: function (transport) {
                                var rslt = eval("(" + transport.responseText + ")");
                                if (rslt.ok) {
                                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                                    var ut = uW.unixtime();
                                    var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                                    for(i = 0; i <= unitsarr.length; i++){
                                        if(params["u"+i]){
                                            unitsarr[i] = params["u"+i];
                                        }
                                    }
                                    var resources=new Array();
                                    resources[0] = params.gold;
                                    for(i=1; i<=5; i++){
                                        resources[i] = params["r"+i];
                                    }
                                    var currentcityid = city;
                                    uW.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                                    uW.update_seed(rslt.updateSeed)
                                    if(rslt.updateSeed){uW.update_seed(rslt.updateSeed)};
                                    actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+" - "+TroopsNeeded+" "+uW.unitcost[unit][0]);
                                } else {
                                    actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+" <font color=red>" + transport.responseText +"</font>");
                                    t.retry++;
                                    if (t.retry>4) {
                                        t.retry=0;
                                    }else {
                                        setTimeout(function() {t.nbcity--;t.actionreappro();},4000);
                                    }
                                }
                            },

                            onFailure: function (rslt) {
                                if (rslt.user_action) {
                                    actionLog(""+culang.mainSupply+"","<b><font color=red>"+culang.movementCaptchaAlert+"</font></b>");
                                    new CdialogCancelContinue('<SPAN class=boldRed>'+culang.supplyCaptchaAlert+'</span>', null, null, mainPop.getMainDiv);

                                } else {
                                    actionLog(""+culang.mainSupply+"","<font color=red>" + rslt.responseText +"</font>");
                                }
                            }

                        });
                    } else {
                        actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+": "+culang.transportSupplyLogNoTroops+"");
                    }
                } else {
                    actionLog(""+culang.mainSupply+"",""+culang.transportSupplyLogTransport+" "+Cities.cities[t.reapproState.city].name+" "+culang.transportSupplyLogTransport2+" "+Cities.cities[t.nbcity].name+": "+culang.transportSupplyLogNoRes+"");
                }
            }
        }
        t.checkdoreapprotimeout = setTimeout(function() { t.actionreappro();}, tempsprochainevisite);
    },
    showAuto: function() {
        var t = Tabs.Transport;
        var m = '<DIV id=pbAutoTransportTab class=pdxStat>'+culang.transportAutoHead+'</div><TABLE id=pbtraderfunctions width=100% height=0% class=pdxTab><TR align="center"><TD><b>'+culang.mainIntervall+'</b>: <INPUT id=pbtransportinterval type=text size=4 value="'+Options.transportinterval+'"\> '+culang.mainMinutes+'</td><TD>'+culang.transportAutoMinTroops+' <INPUT id=pbminwagons type=text size=2 value="'+Options.minwagons+'"\></td><TD><INPUT id=pbShowRoutes type=submit value="'+culang.mainShowRoutes+'"></td>';
        if (t.traderState.running == false) {
            m += '<TD><INPUT id=pbTraderState type=submit value="'+culang.mainTransport+' = '+culang.buttonOFF+' "></td>';
        } else {
            m += '<TD><INPUT id=pbTraderState type=submit value="'+culang.mainTransport+' = '+culang.buttonON+' "></td>';
        }
        m += '</tr></table></div>';

        m += '<DIV id=pbTraderDivDRoute class=pdxStat>'+culang.transportAutoAddRouteHead+'</div>';
        m += '<TABLE id=pbaddtraderoute width=95% height=0% class=pdxTab><TR align="left">';
        m += '<TR align="left"><TD><b>'+culang.mainCastle+'</b>:</td> <TD colspan=4><DIV style="margin-bottom:10px;"><span id=ptrescity></span></div></td></tr>';

        m += '<TR align="left">';
        m += '<TD><b>'+culang.mainTarget+'</b>:</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptcityTo></span></div></td>';
        m += '<TD>'+culang.transportOrTargetCoord+'</td>';
        m += '<TD>X:<INPUT id=ptcityX type=text size=3\></td>';
        m += '<TD>Y:<INPUT id=ptcityY type=text size=3\></td></tr>';
        m += '<TABLE id=pbaddtraderoute height=0% class=pdxTab><TR align="left">';
        m += '<TD width=75px><B>'+culang.transportAutoTroopType+'</b>:</td><TD width=150px><SELECT id="TransportTroop">';
        for (y in uW.unitcost) m+='<option value="'+y+'">'+unsafeWindow.unitcost[y][0]+'</option>';
        m+='</select></td><TD width=75px>'+culang.transportAutoTroopAvailable+'&nbsp;</td><TD id=TroopAmount align=left width=75px></td>';
        m+='<TD width=75px>'+culang.transportAutoTroopAvailableCarry+'&nbsp;</td><TD id=CarryAmount align=left width=75px></td>';
        m += '<TR><TD >'+culang.mainTroops+': </td><TD><INPUT id=TroopsToSend type=text size=6 maxlength=6 value="0">&nbsp;&nbsp;<INPUT id=MaxTroops type=submit value="'+culang.buttonMax+'"></td>';
        m += '<TD width=50px><INPUT id=FillInMax type=submit value="<----"></td>';
        m +='<TD id=Calc colspan=3></td></tr>';
        m += '<TABLE id=pbaddtraderoute height=0% class=pdxTab><TR align="center">';
        m += '<TD width=5%><img src="'+IMGfood30+'"></td>';
        m += '<TD id=TransRec1 align=right width=110px></td>';
        m += '<TD id=HaveRec1 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipFood type=checkbox unchecked=true\></td>';
        m += '<TD width=180px  align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountFood type=text size=11 maxlength=12 value="0" disabled=true\></td>';
        m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountFood type=text size=11 maxlength=12 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxFood type=submit value="'+culang.buttonMax+'"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+IMGwood30+'"></td>';
        m += '<TD id=TransRec2 align=right width=110px></td>';
        m += '<TD id=HaveRec2 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipWood type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountWood type=text size=11 maxlength=12 value="0" disabled=true\></td>';
        m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountWood type=text size=11 maxlength=12 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxWood type=submit value="'+culang.buttonMax+'"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+IMGstone30+'"></td>';
        m += '<TD id=TransRec3 align=right width=110px></td>';
        m += '<TD id=HaveRec3 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipStone type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountStone type=text size=11 maxlength=12 value="0" disabled=true\></td>';
        m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountStone type=text size=11 maxlength=12 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxStone type=submit value="'+culang.buttonMax+'"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+IMGiron30+'"></td>';
        m += '<TD id=TransRec4 align=right width=110px></td>';
        m += '<TD id=HaveRec4 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipOre type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountOre type=text size=11 maxlength=12 value="0" disabled=true\></td>';
        m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountOre type=text size=11 maxlength=12 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxOre type=submit value="'+culang.buttonMax+'"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+IMGastone30+'"></td>';
        m += '<TD id=TransRec5 align=right width=110px></td>';
        m += '<TD id=HaveRec5 align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipAstone type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountAstone type=text size=11 maxlength=12 value="0" disabled=true\></td>';
        m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountAstone type=text size=11 maxlength=12 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxAstone type=submit value="'+culang.buttonMax+'"></td></tr>';
        m += '<TR align="center">';
        m += '<TD width=5%><img src="'+IMGgold30+'"></td>';
        m += '<TD id=TransGold align=right width=110px></td>';
        m += '<TD id=HaveGold align=right width=110px></td>';
        m += '<TD width=55px align=right><INPUT id=pbshipGold type=checkbox unchecked=true\></td>';
        m += '<TD width=180px align=left>'+culang.transportSupplyKeep+' <INPUT id=pbtargetamountGold type=text size=11 maxlength=12 value="0" disabled=true\></td>';
        m += '<TD width=100px>'+culang.mainTransport+': <INPUT id=pbtradeamountGold type=text size=11 maxlength=12 value="0"\></td>';
        m += '<TD width=50px><INPUT id=MaxGold type=submit value="'+culang.buttonMax+'"></td></tr>';

        m += '</table>';

        m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRoute type=submit value="'+culang.transportAutoAddRoute+'"><INPUT id=pbManualSend type=submit value="'+culang.transportButton+'"></div><div style="font-size:10px; color:#555; text-align:center;"> '+culang.transportValue+' </div>';
        m += '<DIV id=errorSpace></div>'

        t.TransportDiv.innerHTML = m;

        ById('TransportTroop').value = 'unt9';

        t.tcp = new CdispCityPicker ('pttrader', ById('ptrescity'), true, t.updateResources, 0);
        t.tcpto = new CdispCityPicker ('pttraderTo', ById('ptcityTo'), true, t.clickCitySelect).bindToXYboxes(document.getElementById ('ptcityX'), document.getElementById ('ptcityY'));


        ById('TransportTroop').addEventListener('change', function(){t.updateTroops();}, false);
        ById('pbTraderState').addEventListener('click', function(){t.toggleTraderState(this);}, false);
        ById('pbSaveRoute').addEventListener('click', function(){t.addTradeRoute();}, false);
        ById('pbManualSend').addEventListener('click', function(){t.ManualTransport();}, false);
        ById('pbShowRoutes').addEventListener('click', function(){t.showTradeRoutes();}, false);
        ById('FillInMax').addEventListener('click', function(){ById('TroopsToSend').value = t.TroopsNeeded;}, false);

        ById('MaxTroops').addEventListener('click', function(){
            var RInfo = getRallypointInfo(t.tcp.city.id);
            if (RInfo.maxMarchSize > t.Troops) ById('TroopsToSend').value = t.Troops;
                else ById('TroopsToSend').value = RInfo.maxMarchSize;
        }, false);
        ById('MaxFood').addEventListener('click', function(){
            t.Food = 0;
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            ById('pbtradeamountFood').value = (parseInt(input) <= parseIntCommas(ById('TransRec1').innerHTML))?input:parseIntCommas(ById('TransRec1').innerHTML);
        }, false);
        ById('MaxWood').addEventListener('click', function(){
            t.Wood = 0;
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            ById('pbtradeamountWood').value = (parseInt(input) <= parseIntCommas(ById('TransRec2').innerHTML))?input:parseIntCommas(ById('TransRec2').innerHTML);
        }, false);
        ById('MaxStone').addEventListener('click', function(){
            t.Stone = 0;
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            ById('pbtradeamountStone').value = (parseInt(input) <= parseIntCommas(ById('TransRec3').innerHTML))?input:parseIntCommas(ById('TransRec3').innerHTML);
        }, false);
        ById('MaxOre').addEventListener('click', function(){
            t.Ore = 0;
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            ById('pbtradeamountOre').value = (parseInt(input) <= parseIntCommas(ById('TransRec4').innerHTML))?input:parseIntCommas(ById('TransRec4').innerHTML);
        }, false);
        ById('MaxGold').addEventListener('click', function(){
            t.Gold = 0;
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            ById('pbtradeamountGold').value = (parseInt(input) <= parseIntCommas(ById('TransGold').innerHTML))?input:parseIntCommas(ById('TransGold').innerHTML);
        }, false);
        ById('MaxAstone').addEventListener('click', function(){
            t.Astone = 0;
            var input = t.MaxLoad - (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone);
            ById('pbtradeamountAstone').value = (parseInt(input) <= parseIntCommas(ById('TransRec5').innerHTML))?input:parseIntCommas(ById('TransRec5').innerHTML);
        }, false);

        ById('pbtransportinterval').addEventListener('keyup', function(){
            if (isNaN(ById('pbtransportinterval').value)){ ById('pbtransportinterval').value=60 ;}
            Options.transportinterval = ById('pbtransportinterval').value;
            saveOptions();
        }, false);

        ById('pbtargetamountFood').addEventListener('keyup', function(){
            if (isNaN(ById('pbtargetamountFood').value)) ById('pbtargetamountFood').value=0 ;
        }, false);
        ById('pbtargetamountWood').addEventListener('keyup', function(){
            if (isNaN(ById('pbtargetamountWood').value)) ById('pbtargetamountWood').value=0 ;
        }, false);
        ById('pbtargetamountStone').addEventListener('keyup', function(){
            if (isNaN(ById('pbtargetamountStone').value)) ById('pbtargetamountStone').value=0 ;
        }, false);
        ById('pbtargetamountOre').addEventListener('keyup', function(){
            if (isNaN(ById('pbtargetamountOre').value)) ById('pbtargetamountOre').value=0 ;
        }, false);
        ById('pbtargetamountAstone').addEventListener('keyup', function(){
            if (isNaN(ById('pbtargetamountAstone').value)) ById('pbtargetamountAstone').value=0 ;
        }, false);
        ById('pbtargetamountGold').addEventListener('keyup', function(){
            if (isNaN(ById('pbtargetamountGold').value)) ById('pbtargetamountGold').value=0 ;
        }, false);
        ById('pbtradeamountFood').addEventListener('keyup', function(){
            if (isNaN(ById('pbtradeamountFood').value)) ById('pbtradeamountFood').value=0 ;
        }, false);
        ById('pbtradeamountWood').addEventListener('keyup', function(){
            if (isNaN(ById('pbtradeamountWood').value)) ById('pbtradeamountWood').value=0 ;
        }, false);
        ById('pbtradeamountStone').addEventListener('keyup', function(){
            if (isNaN(ById('pbtradeamountStone').value)) ById('pbtradeamountStone').value=0 ;
        }, false);
        ById('pbtradeamountOre').addEventListener('keyup', function(){
            if (isNaN(ById('pbtradeamountOre').value)) ById('pbtradeamountOre').value=0 ;
        }, false);
        ById('pbtradeamountAstone').addEventListener('keyup', function(){
            if (isNaN(ById('pbtradeamountAstone').value)) ById('pbtradeamountAstone').value=0 ;
        }, false);
        ById('pbtradeamountGold').addEventListener('keyup', function(){
            if (isNaN(ById('pbtradeamountGold').value)) ById('pbtradeamountGold').value=0 ;
        }, false);
        ById('pbminwagons').addEventListener('keyup', function(){
            if (isNaN(ById('pbminwagons').value)) ById('pbminwagons').value=100 ;
            Options.minwagons = parseInt(ById('pbminwagons').value);
            saveOptions();
        }, false)

        ById('pbshipFood').addEventListener('click', function(){
            if (ById('pbshipFood').checked==false) {
                ById('pbtargetamountFood').disabled = true;
            }
            else {
                ById('pbtargetamountFood').disabled = false;
            }
        },false);
        ById('pbshipWood').addEventListener('click', function(){
            if (ById('pbshipWood').checked==false) {
                ById('pbtargetamountWood').disabled = true;
            }
            else {
                ById('pbtargetamountWood').disabled = false;
            }
        },false);
        ById('pbshipStone').addEventListener('click', function(){
            if (ById('pbshipStone').checked==false) {
                ById('pbtargetamountStone').disabled = true;
            }
            else {
                ById('pbtargetamountStone').disabled = false;
            }
        },false);
        ById('pbshipOre').addEventListener('click', function(){
            if (ById('pbshipOre').checked==false) {
                ById('pbtargetamountOre').disabled = true;
            }
            else {
                ById('pbtargetamountOre').disabled = false;
            }
        },false);
        ById('pbshipAstone').addEventListener('click', function(){
            if (ById('pbshipAstone').checked==false) {
                ById('pbtargetamountAstone').disabled = true;
            }
            else {
                ById('pbtargetamountAstone').disabled = false;
            }
        },false);
        ById('pbshipGold').addEventListener('click', function(){
            if (ById('pbshipGold').checked==false) {
                ById('pbtargetamountGold').disabled = true;
            }
            else {
                ById('pbtargetamountGold').disabled = false;
            }
        },false);

    },
    updateResources2 : function (){
        var t = Tabs.Transport
        t.reapproState.city = t.reacp.city.idx;
        for (var y=0; y< Seed.cities.length;y++) {
            if (t.reacp.city.id==Seed.cities[y][0]) {
                ById('ReappRes_'+y+'_0').value="0";
                ById('ReappRes_'+y+'_0').disabled=true;
            }else {
                ById('ReappRes_'+y+'_0').disabled=false;
                ById('ReappRes_'+y+'_0').value=parseIntNan(t.reapproState['ReappRes_'+y+'_0']);
                ById('ReappRec_'+y+'_0').innerHTML = addCommas ( parseIntNan(Seed.citystats["city" + Seed.cities[y][0]]['gold'][0]) );
            }
            for (var i=1;i<=5;i++) {
                if (t.reacp.city.id==Seed.cities[y][0]) {
                    ById('ReappRes_'+y+'_'+i).value="0";
                    ById('ReappRes_'+y+'_'+i).disabled=true;
                } else{
                    ById('ReappRes_'+y+'_'+i).value= parseIntNan(t.reapproState['ReappRes_'+y+'_'+i]);
                    ById('ReappRes_'+y+'_'+i).disabled=false;
                }
                if(i==5)
                    ById('ReappRec_'+y+'_'+i).innerHTML = addCommas ( parseIntNan(Seed.resources["city" + Seed.cities[y][0]]['rec'+i][0]) );
                else
                    ById('ReappRec_'+y+'_'+i).innerHTML = addCommas ( parseIntNan(Seed.resources["city" + Seed.cities[y][0]]['rec'+i][0]/3600));
            }

        }

    },
    updateResources : function (){
        var t = Tabs.Transport
        var ToCity = null;
        for (var i=1;i<=5;i++)
            if(i==5)
                ById('TransRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + t.tcp.city.id]['rec'+i][0]) );
            else
                ById('TransRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + t.tcp.city.id]['rec'+i][0]/3600) );
        ById('TransGold').innerHTML = addCommas ( parseInt(Seed.citystats["city" + t.tcp.city.id]['gold'][0]) );
        for (ii in Seed.cities)
            if (Seed.cities[ii][2] == document.getElementById ('ptcityX').value && Seed.cities[ii][3] == document.getElementById ('ptcityY').value)
                ToCity = Seed.cities[ii][0];
        for (var i=1;i<=5;i++)
            if (ToCity != null)
                if(i==5)
                    ById('HaveRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + ToCity]['rec'+i][0]) );
                else
                    ById('HaveRec'+i).innerHTML = addCommas ( parseInt(Seed.resources["city" + ToCity]['rec'+i][0]/3600) );
            else ById('HaveRec'+i).innerHTML = "----";
        if (ToCity != null) ById('HaveGold').innerHTML = addCommas ( parseInt(Seed.citystats["city" + ToCity]['gold'][0]) );
        else  ById('HaveGold').innerHTML =  "----";
        t.updateTroops(t.tcp.city.id);
    },

    updateTroops : function (city){
        var t = Tabs.Transport;
        var fontcolor = 'black';
        t.Food = parseInt(ById('pbtradeamountFood').value);
        t.Wood = parseInt(ById('pbtradeamountWood').value);
        t.Stone = parseInt(ById('pbtradeamountStone').value);
        t.Ore = parseInt(ById('pbtradeamountOre').value);
        t.Gold = parseInt(ById('pbtradeamountGold').value);
        t.Astone = parseInt(ById('pbtradeamountAstone').value*5);
        var unit = ById('TransportTroop').value;
        t.Troops = parseInt(Seed.units['city' + t.tcp.city.id][unit]);
        var untid=unit.substr(3);
        
        var techLoadBoost = parseInt(Seed.tech.tch10)*0.1;
        var loadEffectBoost = 0;
        if (Seed.playerEffects.loadExpire > uW.unixtime()) loadEffectBoost = 25;
        var loadBoost = uW.cm.ThroneController.effectBonus(6) + loadEffectBoost;
        if (uW.cm.unitFrontendType[untid]=="siege") {
            if (untid != 9) loadBoost += uW.cm.ThroneController.effectBonus(59);
        } else {
            if (uW.cm.unitFrontendType[untid]=="horsed") {
                loadBoost += uW.cm.ThroneController.effectBonus(48);
            }
        }
        if (loadBoost > 500) {
            loadBoost = 5;
        } else {
            loadBoost = loadBoost * 0.01;
        }
        var LoadUnit = parseInt(parseInt(uW.unitstats[unit][5]) * (1 + loadBoost + techLoadBoost));
        
        var GlobalMaxLoad = t.Troops * LoadUnit;
        t.MaxLoad = parseInt(ById('TroopsToSend').value) * LoadUnit;
        t.TroopsNeeded = (t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) / LoadUnit;
        t.TroopsNeeded = t.TroopsNeeded.toFixed(0);
        if (t.TroopsNeeded < ((t.Food + t.Wood + t.Stone + t.Ore + t.Gold + t.Astone) / LoadUnit)) t.TroopsNeeded++;
        if (t.TroopsNeeded  > t.Troops) fontcolor = 'red';
        if (t.Troops > 0 ) ById('TroopAmount').innerHTML = '<FONT color='+fontcolor+'>' + addCommas(t.Troops) + '</font>';
        else ById('TroopAmount').innerHTML = 0;
        if (GlobalMaxLoad > 0) ById('CarryAmount').innerHTML = addCommas(GlobalMaxLoad);
        else  ById('CarryAmount').innerHTML = 0;
        ById('Calc').innerHTML = ''+culang.mainRessources+': ' +  addCommas(t.Food + t.Wood + t.Stone + t.Ore + t.Gold  + t.Astone) + ' / ' + addCommas(t.MaxLoad) + '&nbsp;&nbsp;('+culang.transportAutoNeedTroops+' <FONT color='+fontcolor+'>' + addCommas(t.TroopsNeeded) + '</font> )' ;
    },

    e_tradeRoutes: function(){
        var t = Tabs.Transport;
        clearTimeout(t.timer2);
        var now = new Date();
        if (t.traderState.running == true)    {
            var now = new Date().getTime()/1000.0;
            now = now.toFixed(0);
            var last = Options.lasttransport;
            if ( now > (parseInt(last) + (Options.transportinterval*60))){
                t.checkdoTrades();
            }
        }
        t.timer2 = setTimeout(function(){ t.e_tradeRoutes();}, Options.transportinterval*60*1000);

    },

    delTradeRoutes: function() {
        var t = Tabs.Transport;
        t.tradeRoutes= [];
    },

    checkcoords : function (obj){
        var t = Tabs.Transport;
        if(obj.id == 'pbok'){
            t.check = true;
            t.addTradeRoute();
        }
        return;
    },

    addTradeRoute: function () {
        var valid = true;
        var t = Tabs.Transport;
        var city = t.tcp.city.id;
        if (ById('ptcityX').value==0 && ById('ptcityY').value ==0 && !t.check)
        {
            return;
        }
        var ship_Food = ById('pbshipFood').checked;
        var ship_Wood = ById('pbshipWood').checked;
        var ship_Stone = ById('pbshipStone').checked;
        var ship_Ore = ById('pbshipOre').checked;
        var ship_Astone = ById('pbshipAstone').checked;
        var ship_Gold = ById('pbshipGold').checked;
        var target_Food = ById('pbtargetamountFood').value;
        var target_Wood = ById('pbtargetamountWood').value;
        var target_Stone = ById('pbtargetamountStone').value;
        var target_Ore = ById('pbtargetamountOre').value;
        var target_Astone = ById('pbtargetamountAstone').value;
        var target_Gold = ById('pbtargetamountGold').value;
        var trade_Food = ById('pbtradeamountFood').value;
        var trade_Wood = ById('pbtradeamountWood').value;
        var trade_Stone = ById('pbtradeamountStone').value;
        var trade_Ore = ById('pbtradeamountOre').value;
        var trade_Astone = ById('pbtradeamountAstone').value;
        var trade_Gold = ById('pbtradeamountGold').value;
        var target_x = ById('ptcityX').value;
        var target_y = ById('ptcityY').value;
        var target_CityId = 0;
        for (var ii in Seed.cities)
            if (Seed.cities[ii][2] == target_x && Seed.cities[ii][3] == target_y)
                target_CityId = Seed.cities[ii][0];
        var TroopType = ById('TransportTroop').value;
        var route_state = true;

        if (valid == true) {
            var lTR = t.tradeRoutes;
            lTR.push({
                city:                        city,
                ship_Food:            ship_Food,
                target_Food:        target_Food,
                trade_Food:         trade_Food,
                ship_Wood:            ship_Wood,
                target_Wood:        target_Wood,
                trade_Wood:         trade_Wood,
                ship_Stone:            ship_Stone,
                target_Stone:        target_Stone,
                trade_Stone:         trade_Stone,
                ship_Ore:                ship_Ore,
                target_Ore:            target_Ore,
                trade_Ore:             trade_Ore,
                ship_Astone:      ship_Astone,
                target_Astone:    target_Astone,
                trade_Astone:         trade_Astone,
                ship_Gold:            ship_Gold,
                target_Gold:        target_Gold,
                trade_Gold:         trade_Gold,
                target_x:             target_x,
                target_y:             target_y,
                target_CityId:    target_CityId,
                TroopType:      TroopType,
                route_state:         "true"
            });
        }
        ById('pbTraderDivDRoute').style.background ='#99FF99';
        setTimeout(function(){ (ById('pbTraderDivDRoute').style.background =''); }, 500);
    },
    showTradeRoutes: function () {
        var t = Tabs.Transport;
        if (t.popTradeRoutes == null) {
            t.popTradeRoutes = new CPopup('pbShowTrade', 0, 0, 750, 500, true, function() {clearTimeout (1000);});
            t.popTradeRoutes.centerMe (mainPop.getMainDiv());
        }
        var m = '<DIV style="max-height:450px; overflow:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pdxTab" id="pbRoutesQueue">';
        t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
        t.popTradeRoutes.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.transportAutoRoutes+'</div>';
        t.paintTradeRoutes();
        t.popTradeRoutes.show(true)    ;
    },
    paintTradeRoutes: function(){
        var t = Tabs.Transport;
        var r = t.tradeRoutes;
        var cityname;
        var citynameTo = null;
        var m= '<TABLE id=paintRoutes class=pdxTab>';
        for (var i=0;i<(r.length);i++) {
            citynameTo = null;
            for (var y=0; y< Seed.cities.length;y++) {
                if ( parseInt(Seed.cities[y][0]) == r[i].city) var cityname = Seed.cities[y][1];
                if (r[i].target_CityId && r[i].target_CityId != 0) {
                    r[i].target_x = Cities.byID[r[i].target_CityId].x;
                    r[i].target_y = Cities.byID[r[i].target_CityId].y;
                }
                if ( parseInt(Seed.cities[y][2]) == r[i].target_x && parseInt(Seed.cities[y][3]) == r[i].target_y) var citynameTo = Seed.cities[y][1];
            }
            var queueId = i;
            if (citynameTo == null) var TO = r[i].target_x +','+ r[i].target_y;
            else TO = citynameTo;
            if (r[i].route_state) var status = '<FONT color=green>'+culang.transportAutoRoutesActive+'</font>';
            else var status = '<FONT color=red>'+culang.transportAutoRoutesDisabled+'</font>';
            if (r[i].TroopType == undefined) var unit = 'unt9';
            else var unit = r[i].TroopType;
            m += '<TR><TD TD width=12px>&nbsp;&nbsp;</td></tr>';
            m +='<TR><TD width=20px>'+(i+1)+'</td><TD width=175px><u>'+culang.mainFrom+'</u>:&nbsp;&nbsp;'+ cityname +'</TD><TD width=175px><u>'+culang.mainTo+'</u>:&nbsp;&nbsp;'+ TO +'</td><TD width=175px>'+status+'</td>';
            m +='<TD width=60px><A onclick="traceEdit('+queueId+')">'+culang.buttonEdit+'</a></td><TD width=60px><A onclick="traceDelete('+queueId+')"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></a></td></tr>';
            m += '<TR><TD></td><TD>'+culang.mainTroops+':&nbsp;&nbsp;'+unsafeWindow.unitcost[unit][0]+'</td></tr>';
            if (r[i].ship_Food) m += '<TR><TD></td><TD align=center><img src="'+IMGfood30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Food) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Food)+'</td>';
            if (r[i].ship_Wood) m += '<TR><TD></td><TD align=center><img src="'+IMGwood30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Wood) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Wood)+'</td>';
            if (r[i].ship_Stone) m += '<TR><TD></td><TD align=center><img src="'+IMGstone30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Stone) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Stone)+'</td>';
            if (r[i].ship_Ore) m += '<TR><TD></td><TD align=center><img src="'+IMGiron30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Ore) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Ore)+'</td>';
            if (r[i].ship_Astone) m += '<TR><TD></td><TD align=center><img src="'+IMGastone30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Astone) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Astone)+'</td>';
            if (r[i].ship_Gold) m += '<TR><TD></td><TD align=center><img src="'+IMGgold30+'"></td><TD>'+culang.transportSupplyKeep+' '+ addCommas(r[i].target_Gold) +'</td><TD>'+culang.mainTransport+': '+ addCommas(r[i].trade_Gold)+'</td>';
        }
        m +='</table>';
        ById('pbRoutesQueue').innerHTML= m;
        unsafeWindow.traceEdit = t.editQueueElement;
        unsafeWindow.traceDelete = t.cancelQueueElement;
    },

    cancelQueueElement: function(queueId){
        var t = Tabs.Transport;
        var queueId = parseInt(queueId);
        t.tradeRoutes.splice(queueId, 1);
        t.showTradeRoutes();
    },

    editQueueElement: function(queueId){
        var t = Tabs.Transport;
        var r = t.tradeRoutes;
        var queueId = parseInt(queueId);
        var cityname;
        var citynameTo = null;
        var Types = ['food','wood','stone','iron','aetherstone','gold'];
        for (var y=0; y< Seed.cities.length;y++) {
            if ( parseInt(Seed.cities[y][0]) == r[queueId].city) var cityname = Seed.cities[y][1];
            if ( parseInt(Seed.cities[y][2]) == r[queueId].target_x && parseInt(Seed.cities[y][3]) == r[queueId].target_y) var citynameTo = Seed.cities[y][1];
        }
        if (citynameTo == null) var TO = r[queueId].target_x +','+ r[queueId].target_y;
        else TO = citynameTo;
        var n = '<TABLE id=editRoutes class=pdxTab>';
        n +='<TD><u>'+culang.mainFrom+'</u>:&nbsp;'+ cityname +'</td><TD><u>'+culang.mainTo+'</u>:&nbsp;'+ TO +'</td>';
        n +='<TD><INPUT id=TradeStatus type=checkbox>&nbsp;'+culang.transportAutoActivateRoute+'</td>';
        n += '<TD width=150px><b>'+culang.mainTroops+'</b>: <SELECT id="pbbTransportTroop">';
        for (y in unsafeWindow.unitcost) n+='<option value="'+y+'">'+unsafeWindow.unitcost[y][0]+'</option>';
        n+='</select></td></table><BR><TABLE  id=editRoutes class=pdxTab>';
        for (var i=0;i<Types.length;i++){
            var icon = Types[i];
            n += '<TR><TD width=50px align=center><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/'+icon+'_30.png"></td>';
            n += '<TD width=50px align=center><INPUT id=pbbship'+Types[i]+' type=checkbox></td>';
            n += '<TD width=125px>'+culang.transportSupplyKeep+' <INPUT id=pbbtargetamount'+Types[i]+' type=text size=11 maxlength=12 value="0"></td>';
            n += '<TD width=125px>'+culang.mainTransport+': <INPUT id=pbbtradeamount'+Types[i]+' type=text size=11 maxlength=12 value="0"\></td></tr>';
        }
        n+='</table><BR><TABLE id=editRoutes class=pdxTab><TR><TD><a id="Cancel"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></span></a></td>';
        n+='<TD><a class="button20" id="Save"><span>'+culang.buttonSave+'</span></a></td></tr>';
        n +='</table>';

        ById('pbRoutesQueue').innerHTML= n;
        ById('TradeStatus').checked = r[queueId].route_state;
        if (r[queueId].TroopType == undefined) var unit = 'unt9';
        else var unit = r[queueId].TroopType;
        ById('pbbTransportTroop').value = unit;
        ById('pbbshipfood').checked = r[queueId].ship_Food;
        ById('pbbshipwood').checked = r[queueId].ship_Wood;
        ById('pbbshipstone').checked = r[queueId].ship_Stone;
        ById('pbbshipiron').checked = r[queueId].ship_Ore;
        ById('pbbshipaetherstone').checked = r[queueId].ship_Astone;
        ById('pbbshipgold').checked = r[queueId].ship_Gold;
        ById('pbbtargetamountfood').value = r[queueId].target_Food;
        ById('pbbtargetamountwood').value = r[queueId].target_Wood;
        ById('pbbtargetamountstone').value = r[queueId].target_Stone;
        ById('pbbtargetamountiron').value = r[queueId].target_Ore;
        ById('pbbtargetamountaetherstone').value = r[queueId].target_Astone;
        ById('pbbtargetamountgold').value = r[queueId].target_Gold;
        ById('pbbtradeamountfood').value = r[queueId].trade_Food;
        ById('pbbtradeamountwood').value = r[queueId].trade_Wood;
        ById('pbbtradeamountstone').value = r[queueId].trade_Stone;
        ById('pbbtradeamountiron').value = r[queueId].trade_Ore;
        ById('pbbtradeamountaetherstone').value = r[queueId].trade_Astone;
        ById('pbbtradeamountgold').value = r[queueId].trade_Gold;
        ById('Cancel').addEventListener('click', function(){t.showTradeRoutes();}, false);
        ById('Save').addEventListener('click', function(){
            r[queueId].route_state = ById('TradeStatus').checked;
            r[queueId].TroopType = ById('pbbTransportTroop').value;
            r[queueId].ship_Food = ById('pbbshipfood').checked;
            r[queueId].ship_Wood = ById('pbbshipwood').checked;
            r[queueId].ship_Stone = ById('pbbshipstone').checked;
            r[queueId].ship_Ore = ById('pbbshipiron').checked;
            r[queueId].ship_Astone = ById('pbbshipaetherstone').checked;
            r[queueId].ship_Gold = ById('pbbshipgold').checked;
            r[queueId].target_Food = ById('pbbtargetamountfood').value;
            r[queueId].target_Wood = ById('pbbtargetamountwood').value;
            r[queueId].target_Stone = ById('pbbtargetamountstone').value;
            r[queueId].target_Ore = ById('pbbtargetamountiron').value;
            r[queueId].target_Astone = ById('pbbtargetamountaetherstone').value;
            r[queueId].target_Gold = ById('pbbtargetamountgold').value;
            r[queueId].trade_Food = ById('pbbtradeamountfood').value;
            r[queueId].trade_Wood = ById('pbbtradeamountwood').value;
            r[queueId].trade_Stone = ById('pbbtradeamountstone').value;
            r[queueId].trade_Ore = ById('pbbtradeamountiron').value;
            r[queueId].trade_Astone = ById('pbbtradeamountaetherstone').value;
            r[queueId].trade_Gold = ById('pbbtradeamountgold').value;
            t.showTradeRoutes();
        }, false);
    },

    saveTradeRoutes: function(){
        var t = Tabs.Transport;
        var serverID = getServerId();
        GM_setValue('tradeRoutes_' + serverID, JSON2.stringify(t.tradeRoutes));
    },
    readTradeRoutes: function(){
        var t = Tabs.Transport;
        var serverID = getServerId();
        s = GM_getValue('tradeRoutes_' + serverID);
        if (s != null) {
            route = JSON2.parse(s);
            for (k in route)
                t.tradeRoutes[k] = route[k];
        }
    },
    saveTraderState: function(){
        var t = Tabs.Transport;
        var serverID = getServerId();
        GM_setValue('traderState_' + serverID, JSON2.stringify(t.traderState));
    },
    readTraderState: function(){
        var t = Tabs.Transport;
        var serverID = getServerId();
        s = GM_getValue('traderState_' + serverID);
        if (s != null) {
            state = JSON2.parse(s);
            for (k in state)
                t.traderState[k] = state[k];
        }
    },
    toggleTraderState: function(obj){
        var t = Tabs.Transport;
        obj = ById('pbTraderState');
        if (t.traderState.running == true) {
            t.traderState.running = false;
            if (obj)  obj.value = culang.mainTransport+" = "+culang.buttonOFF;
            clearTimeout(t.checkdotradetimeout);
            clearTimeout(t.timer2);
            t.count = 0;
            Options.lasttransport = 0;
            saveOptions();
        }
        else {
            t.traderState.running = true;
            if (obj) obj.value = culang.mainTransport+" = "+culang.buttonON;
            t.e_tradeRoutes();
        }
    },

    checkdoTrades: function(){
        var t = Tabs.Transport;
        if(t.tradeRoutes.length==0) return;
        t.doTrades(t.count);
        t.count++;
        if(t.count < t.tradeRoutes.length){
            t.checkdotradetimeout = setTimeout(function() { t.checkdoTrades();}, 5000);
        } else {
            var now = new Date().getTime()/1000.0;
            now = now.toFixed(0);
            Options.lasttransport = now;
            saveOptions();
            t.count = 0;
        }
    },

    doTrades: function(count){
        var t = Tabs.Transport;

        if(t.tradeRoutes.length==0) return;
        if(!t.tradeRoutes[count]["route_state"]) return;

        var city = t.tradeRoutes[count]["city"];
        if(!Cities.byID[city]) return;

        if (t.tradeRoutes[count].target_CityId && t.tradeRoutes[count].target_CityId != 0) {
            t.tradeRoutes[count].target_x = Cities.byID[t.tradeRoutes[count].target_CityId].x;
            t.tradeRoutes[count].target_y = Cities.byID[t.tradeRoutes[count].target_CityId].y;
        }
        
        var xcoord = t.tradeRoutes[count]["target_x"];
        var ycoord = t.tradeRoutes[count]["target_y"];
        var cityID = 'city' + city;
        var toCityName = '';
        for (var zz=0; zz< Seed.cities.length;zz++) {
            if (parseInt(Seed.cities[zz][0]) == city) {
                var cityname = Seed.cities[zz][1];
            }
            if (parseInt(Seed.cities[zz][2]) == xcoord && parseInt(Seed.cities[zz][3]) == ycoord) {
                toCityName = ' ('+Seed.cities[zz][1]+')';
            }
        }
        var RInfo = getRallypointInfo(city);
        if(RInfo.usedSlots >= RInfo.maxMarches){
            actionLog(""+culang.mainTransport+"",""+culang.transportSupplyLogTransport+" "+cityname+" "+culang.transportSupplyLogTransport2+" " + xcoord + "," + ycoord + " <font color=red>"+culang.transportSupplyLogFullRP+"</font>");
            return;
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.gold =0;
        params.r1 =0;
        params.r2 =0;
        params.r3 =0;
        params.r4 =0 ;
        params.r5 =0 ;
        params.kid = 0;

        var carry_amount= 0;
        var wagons_needed=0;
        var citymax = 0;

        var trade_Food = t.tradeRoutes[count]["trade_Food"];
        var trade_Wood = t.tradeRoutes[count]["trade_Wood"];
        var trade_Stone = t.tradeRoutes[count]["trade_Stone"];
        var trade_Ore = t.tradeRoutes[count]["trade_Ore"];
        var trade_Astone = t.tradeRoutes[count]["trade_Astone"];
        var trade_Gold = t.tradeRoutes[count]["trade_Gold"];
        var target_Food = t.tradeRoutes[count]["target_Food"];
        var target_Wood = t.tradeRoutes[count]["target_Wood"];
        var target_Stone = t.tradeRoutes[count]["target_Stone"];
        var target_Ore = t.tradeRoutes[count]["target_Ore"];
        var target_Astone = t.tradeRoutes[count]["target_Astone"];
        var target_Gold = t.tradeRoutes[count]["target_Gold"];
        var ship_Food = t.tradeRoutes[count]["ship_Food"];
        var ship_Wood = t.tradeRoutes[count]["ship_Wood"];
        var ship_Stone = t.tradeRoutes[count]["ship_Stone"];
        var ship_Ore = t.tradeRoutes[count]["ship_Ore"];
        var ship_Astone = t.tradeRoutes[count]["ship_Astone"];
        var ship_Gold = t.tradeRoutes[count]["ship_Gold"];
        var citymax_Food = parseIntNan(Seed.resources[cityID]['rec1'][0] / 3600);
        var citymax_Wood = parseIntNan(Seed.resources[cityID]['rec2'][0] / 3600);
        var citymax_Stone = parseIntNan(Seed.resources[cityID]['rec3'][0] / 3600);
        var citymax_Ore = parseIntNan(Seed.resources[cityID]['rec4'][0] / 3600);
        var citymax_Astone = parseIntNan(Seed.resources[cityID]['rec5'][0]);
        var citymax_Gold = parseIntNan(Seed.citystats[cityID]['gold']);
        var carry_Food = parseIntNan(citymax_Food - target_Food);
        var carry_Wood = parseIntNan(citymax_Wood - target_Wood);
        var carry_Stone = parseIntNan(citymax_Stone - target_Stone);
        var carry_Ore = parseIntNan(citymax_Ore - target_Ore);
        var carry_Astone = parseIntNan(citymax_Astone - target_Astone);
        var carry_Gold = 0;
        if (carry_Food < 0 || ship_Food==false) carry_Food = 0;
        if (carry_Wood < 0 || ship_Wood==false) carry_Wood = 0;
        if (carry_Stone < 0 || ship_Stone==false) carry_Stone = 0;
        if (carry_Ore < 0 || ship_Ore==false) carry_Ore = 0;
        if (carry_Astone < 0 || ship_Astone==false) carry_Astone = 0;
        if (trade_Food > 0 && (carry_Food > trade_Food)) carry_Food = parseIntNan(trade_Food);
        if (trade_Wood > 0 && (carry_Wood > trade_Wood)) carry_Wood = parseIntNan(trade_Wood);
        if (trade_Stone > 0 && (carry_Stone > trade_Stone)) carry_Stone = parseIntNan(trade_Stone);
        if (trade_Ore > 0 && (carry_Ore > trade_Ore)) carry_Ore = parseIntNan(trade_Ore);
        if (trade_Astone > 0 && (carry_Astone > trade_Astone)) carry_Astone = parseIntNan(trade_Astone);
        carry_Astone *= 5;
        if (t.tradeRoutes[count]['TroopType'] == undefined) var wagons = parseInt(Seed.units[cityID]['unt'+ 9]);
        else var wagons =  parseInt(Seed.units[cityID][t.tradeRoutes[count]['TroopType']]);
        if (parseInt(wagons) > RInfo.maxMarchSize){ wagons = RInfo.maxMarchSize; }
        if (t.tradeRoutes[count]['TroopType'] == undefined) var unit = 'unt9';
        else var unit = t.tradeRoutes[count]['TroopType'];
        var Troops = parseInt(Seed.units[cityID][unit]);
        if(parseInt(Troops)>parseInt(wagons)) Troops = wagons;
        var untid = unit.substr(3);
        var techLoadBoost = parseInt(Seed.tech.tch10)*0.1;
        var loadEffectBoost = 0;
        if (Seed.playerEffects.loadExpire > uW.unixtime()) loadEffectBoost = 25;
        var loadBoost = uW.cm.ThroneController.effectBonus(6) +loadEffectBoost;
        if (uW.cm.unitFrontendType[untid]=="siege") {
            if (untid != 9) loadBoost += uW.cm.ThroneController.effectBonus(59);
        } else {
            if (uW.cm.unitFrontendType[untid]=="horsed") {
                loadBoost += uW.cm.ThroneController.effectBonus(48);
            }
        }
        if (loadBoost > 500) {
            loadBoost = 5;
        } else {
            loadBoost = loadBoost * 0.01;
        }
        var maxloadperwagon = parseInt(parseInt(uW.unitstats[unit][5]) * (1 + loadBoost + techLoadBoost));
        var maxload = (maxloadperwagon * Troops);
        if(wagons <= 0) {return; }
        var shift_Food = parseIntNan(maxload / 9);
        var shift_Wood = parseIntNan(maxload / 9);
        var shift_Stone = parseIntNan(maxload / 9);
        var shift_Ore = parseIntNan(maxload / 9);
        var shift_Astone = parseIntNan(maxload / 9 * 5);
        if ((maxload - carry_Food - carry_Wood - carry_Stone - carry_Ore - carry_Astone) < 0){
            var shift_num=0;
            var shift_spare=0;
            if (carry_Food < shift_Food) {
                shift_spare += (shift_Food - carry_Food);
                shift_Food = carry_Food;
            }
            if (carry_Wood < shift_Wood) {
                shift_spare += (shift_Wood - carry_Wood);
                shift_Wood = carry_Wood;
            }
            if (carry_Stone < shift_Stone) {
                shift_spare += (shift_Stone - carry_Stone);
                shift_Stone = carry_Stone;
            }
            if (carry_Ore < shift_Ore) {
                shift_spare += (shift_Ore - carry_Ore);
                shift_Ore = carry_Ore;
            }
            if (carry_Astone < shift_Astone) {
                shift_spare += (shift_Astone - carry_Astone);
                shift_Astone = carry_Astone;
            }

            while (shift_spare >1) {
                if (carry_Food < (shift_Food + shift_spare)){
                    shift_spare = shift_spare - carry_Food;;
                    shift_Food = carry_Food;
                }
                else{
                    shift_Food = (shift_Food + shift_spare);
                    shift_spare = shift_spare- shift_spare;
                }
                if (carry_Wood < (shift_Wood + shift_spare)){
                    shift_spare = shift_spare - carry_Wood;;
                    shift_Wood = carry_Wood;
                }
                else{
                    shift_Wood = shift_Wood + shift_spare;
                    shift_spare = shift_spare- shift_spare;
                }
                if (carry_Stone < (shift_Stone + shift_spare)){
                    shift_spare = shift_spare - carry_Stone;
                    shift_Stone = carry_Stone;
                }
                else{
                    shift_Stone = shift_Stone + shift_spare;
                    shift_spare = shift_spare- shift_spare;
                }
                if (carry_Ore < (shift_Ore + shift_spare)){
                    shift_spare = shift_spare - carry_Ore;
                    shift_Ore = carry_Ore;
                }
                else{
                    shift_Ore = shift_Ore + shift_spare;
                    shift_spare = shift_spare- shift_spare;
                }
                if (carry_Astone < (shift_Astone + shift_spare)){
                    shift_spare = shift_spare - carry_Astone;
                    shift_Astone = carry_Astone;
                }
                else{
                    shift_Astone = shift_Astone + shift_spare;
                    shift_spare = shift_spare- shift_spare;
                }
            }

            carry_Food = shift_Food;
            carry_Wood = shift_Wood;
            carry_Stone = shift_Stone;
            carry_Ore = shift_Ore;
            carry_Astone = shift_Astone;
        }

        if (maxload > (carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone) && ship_Gold==true) {
            if ((maxload-(carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone)) > (citymax_Gold - target_Gold)){
                carry_Gold = (citymax_Gold - target_Gold);
                if (carry_Gold < 0 ) carry_Gold = 0;
            }
            else carry_Gold = (maxload-(carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone));
            if (trade_Gold > 0 && (carry_Gold > trade_Gold)) carry_Gold = parseInt(trade_Gold);
        }

        wagons_needed = ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) / maxloadperwagon);
        wagons_needed = wagons_needed.toFixed(0);
        if (wagons_needed < ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) / maxloadperwagon)) wagons_needed++;
        if ( wagons_needed < Options.minwagons ) { return; }

        params.cid= city;
        params.type = "1";
        params.xcoord = xcoord;
        params.ycoord = ycoord;
        params.r1 = carry_Food;
        params.r2 = carry_Wood;
        params.r3 = carry_Stone;
        params.r4 = carry_Ore;
        params.r5 = parseInt(carry_Astone/5);
        params.gold = carry_Gold;

        switch (unit){
            case 'unt1': params.u1 = wagons_needed;break;
            case 'unt2': params.u2 = wagons_needed;break;
            case 'unt3': params.u3 = wagons_needed;break;
            case 'unt4': params.u4 = wagons_needed;break;
            case 'unt5': params.u5 = wagons_needed;break;
            case 'unt6': params.u6 = wagons_needed;break;
            case 'unt7': params.u7 = wagons_needed;break;
            case 'unt8': params.u8 = wagons_needed;break;
            case 'unt9': params.u9 = wagons_needed;break;
            case 'unt10': params.u10 = wagons_needed;break;
            case 'unt11': params.u11 = wagons_needed;break;
            case 'unt12': params.u12 = wagons_needed;break;
            case 'unt13': params.u13 = wagons_needed;break;
            case 'unt14': params.u14 = wagons_needed;break;
            case 'unt15': params.u15 = wagons_needed;break;
        }
        if ((carry_Food + carry_Wood + carry_Stone + carry_Ore + carry_Astone + carry_Gold) > 0) {

            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                loading: true,
                onSuccess: function (transport) {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                        var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                        var ut = unsafeWindow.unixtime();
                        var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                        for(i = 0; i <= unitsarr.length; i++){
                            if(params["u"+i]){
                                unitsarr[i] = params["u"+i];
                            }
                        }
                        var resources=new Array();
                        resources[0] = params.gold;
                        for(i=1; i<=5; i++){
                            resources[i] = params["r"+i];
                        }
                        var currentcityid = city;
                        unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                        unsafeWindow.update_seed(rslt.updateSeed)
                        if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                        actionLog(""+culang.mainTransport+"",""+culang.transportAutoLog+" " + cityname + " "+culang.transportAutoLog2+" " + xcoord + ',' + ycoord + toCityName + "  -> "+ unsafeWindow.unitcost[unit][0] +": " + wagons_needed);
                    } else {
                        actionLog(""+culang.mainTransport+"",""+culang.transportAutoLog+" " + cityname + " "+culang.transportAutoLog2+" " + xcoord + ',' + ycoord + toCityName + "<br><font color=red>" + uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)) + "</font>");
                    }
                },
                onFailure: function (transport) {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.user_action) {
                        actionLog(""+culang.mainTransport+"","<b><font color=red>"+culang.movementCaptchaAlert+"</font></b>");
                        new CdialogCancelContinue('<SPAN class=boldRed>'+culang.transportCaptchaAlert+'</span>', null, null, mainPop.getMainDiv);
                    }else{
                        actionLog(""+culang.mainTransport+"",""+culang.transportAutoLog+" " + cityname + " "+culang.transportAutoLog2+" " + xcoord + ',' + ycoord + toCityName + "<br><font color=red>" + uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)) + "</font>");
                    }
                }

            });
        }
    },

    ManualTransport: function(){
        var t = Tabs.Transport;
        if (document.getElementById ('ptcityX').value == "" || document.getElementById ('ptcityY').value == "") return;
        if ( t.TroopsNeeded > t.Troops) return;

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        var unitType = ById('TransportTroop').value;
        var untid=unitType.substr(3);
        var techLoadBoost = parseInt(Seed.tech.tch10)*0.1;
        var loadEffectBoost = 0;
        if (Seed.playerEffects.loadExpire > uW.unixtime()) loadEffectBoost = 25;
        var loadBoost = uW.cm.ThroneController.effectBonus(6) +loadEffectBoost;
        if (uW.cm.unitFrontendType[untid]=="siege") {
            if (untid != 9) loadBoost += uW.cm.ThroneController.effectBonus(59);
        } else {
            if (uW.cm.unitFrontendType[untid]=="horsed") {
                loadBoost += uW.cm.ThroneController.effectBonus(48);
            }
        }
        if (loadBoost > 500) {
            loadBoost = 5;
        } else {
            loadBoost = loadBoost * 0.01;
        }
        var LoadUnit = parseInt(parseInt(uW.unitstats[unitType][5]) * (1 + loadBoost + techLoadBoost));
        var MaxLoad =  parseInt(Seed.units['city' + t.tcp.city.id][unitType]) * LoadUnit;
        document.getElementById ('errorSpace').innerHTML = '';

        params.kid = 0;
        params.cid=  t.tcp.city.id;
        params.type = "1";
        params.xcoord = parseInt(document.getElementById ('ptcityX').value);
        params.ycoord = parseInt(document.getElementById ('ptcityY').value);
        params.r1 = parseInt(document.getElementById ('pbtradeamountFood').value);
        params.r2 = parseInt(document.getElementById ('pbtradeamountWood').value);
        params.r3 = parseInt(document.getElementById ('pbtradeamountStone').value);
        params.r4 = parseInt(document.getElementById ('pbtradeamountOre').value);
        params.r5 = parseInt(document.getElementById ('pbtradeamountAstone').value);
        params.gold = parseInt(document.getElementById ('pbtradeamountGold').value);

        switch (unitType){
            case 'unt1': params.u1 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt2': params.u2 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt3': params.u3 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt4': params.u4 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt5': params.u5 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt6': params.u6 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt7': params.u7 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt8': params.u8 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt9': params.u9 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt10': params.u10 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt11': params.u11 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt12': params.u12 = parseInt(document.getElementById ('TroopsToSend').value);break;
            case 'unt13': params.u13 = parseInt(document.getElementById ('TroopsToSend').value);break;        
            case 'unt14': params.u14 = parseInt(document.getElementById ('TroopsToSend').value);break;        
            case 'unt15': params.u15 = parseInt(document.getElementById ('TroopsToSend').value);break;    
        }

        if ((params.r1 + params.r2 + params.r3 + params.r4 + params.r5 + params.gold) > 0) {
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                loading: true,
                onSuccess: function (transport) {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                        var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                        var ut = unixTime();
                        var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                        for(i = 0; i <= unitsarr.length; i++){
                            if(params["u"+i]){
                                unitsarr[i] = params["u"+i];
                            }
                        }
                        var resources=new Array();
                        resources[0] = params.gold;
                        for(i=1; i<=5; i++){
                            resources[i] = params["r"+i];
                        }
                        var currentcityid = t.tcp.city.id;
                        unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                        if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                        document.getElementById ('errorSpace').innerHTML = ''+culang.transportSend+' ' + addCommas(params.r1+params.r2+params.r3+params.r4+params.r5+params.gold) + ' '+culang.transportSend2+' ' + addCommas(parseInt(document.getElementById ('TroopsToSend').value)) + ' ' + unsafeWindow.unitcost[unitType][0];
                        document.getElementById ('pbtradeamountFood').value = 0;
                        document.getElementById ('pbtradeamountWood').value = 0;
                        document.getElementById ('pbtradeamountStone').value = 0;
                        document.getElementById ('pbtradeamountOre').value = 0;
                        document.getElementById ('pbtradeamountAstone').value = 0;
                        document.getElementById ('pbtradeamountGold').value = 0;
                        document.getElementById ('TroopsToSend').value = 0;
                    } else {
                        var errorcode =  'err_' + rslt.error_code;
                        if (rlst.msg == undefined)document.getElementById ('errorSpace').innerHTML = '<HR><FONT COLOR=red>'+culang.mainError+': ' + unsafeWindow.g_js_strings.errorcode[errorcode] +'</font>';
                        else document.getElementById ('errorSpace').innerHTML = '<HR><FONT COLOR=red>'+culang.mainError+': ' + rslt.msg +'</font>';
                    }
                },
                onFailure: function () {}
            });
        }
    },

    onUnload: function(){
        var t = Tabs.Transport;
        if (!ResetAll) t.saveTradeRoutes();
        if (!ResetAll) t.saveTraderState();
        if (!ResetAll) t.saveReapproState();
    },
    showManuel : function() {
        var t = Tabs.Transport
        var rownum = 0;

        var ModelCity = {};

        function _row (name, row, noTotal){
            if (rownum++ % 2)
                style = '';
            else
                style = ' style = "background: #e8e8e8"';
            var tot = 0;
            var m = [];
            m.push ('<TR style="background: #fff" align=right');
            m.push (style);
            m.push ('><TD');
            m.push (style);
            m.push ('><B>');
            m.push (name);
            m.push ('</td>');
            if (noTotal){
                m.push ('<TD');
                m.push (style);
                m.push ('>&nbsp;</td>');
            } else {
                for (i=0; i<row.length; i++)
                    tot += row[i];
                m.push ('<TD style="background: #ffc">');
                m.push (addCommas(tot));
                m.push ('</td>');
            }
            for (i=0; i<row.length; i++){
                m.push ('<TD');
                m.push (style);
                m.push ('>');
                m.push (addCommas(row[i]));
                m.push ('</td>');
            }
            m.push ('</tr>');
            return m.join('');
        }
        dt = new Date ();
        dt.setTime (Seed.player.datejoinUnixTime * 1000);
        if (t.state == null) {
            m = "<DIV class=pdxStat>"+culang.transportHead+"</div>";
            m +="<div id=ptTranportStatus style='text-align:center;overflow-y:auto; max-height:78px; border-bottom:1px solid #141516;'></div>";
            m += "<TABLE width=100% class=pdxTab border=0>\
       <tr align=center><td colspan=2></td></tr>\
       <tr align=center valign=top><td colspan=1 width=50%><b><u>"+culang.mainCastle+"</b></u><br><span id=srcptspeedcity></span></td>\
       <td colspan=1 width=50%  rowspan=2><b><u>"+culang.mainTarget+"</b></u><br><span id=desptspeedcity></span><br>\
       "+culang.transportOrTargetCoord+" <br>X: <input type=text size=4 id=typetrpx value=0>&nbsp;Y: <input type=text size=4 id=typetrpy value=0><br><a href='javascript:void(0);' id='chargelistelieux'>"+culang.mainPlayer+"</a>: <select id='KslisteFavori'></select><br><br><INPUT id='ptttButTransport' type=submit value='"+culang.transportButton+"' style='font-weight:bold'>\
       </td></tr>\
       <tr align=center><td colspan=1><b>"+culang.mainTroops+":</b> <select id=typetrp><option selected value='1'>"+culang.shrsupply+"</option><option selected value='9'>"+culang.shrsupplywagon+"</option><option value='7'>"+culang.shrcavalry+"</option><option value='8'>"+culang.shrheavycavalry+"</option></select>\
       <br><b>"+culang.mainAmount+":</b> <input type=text size=6 value='1000' id='Choixnbwagon'><input type=button id='trswagmax' value='"+culang.buttonMax+"'\><br>\
       <br><b>"+culang.mainRessources+":</b> <input type=radio id='ChoixRess0' name='ChoixRess' value='gold' style='visibility:hidden'><img src='"+IMGgold30+"' onclick=document.getElementById('ChoixRess0').checked=true;Ksestimeres(); height=20 title='"+culang.transportGoldNote+"'>\
       <input type=radio id='ChoixRess1' name='ChoixRess' value='rec1' style='visibility:hidden'><img src='"+IMGfood30+"' onclick=document.getElementById('ChoixRess1').checked=true;Ksestimeres(); height=20 title='"+culang.transportFoodNote+"'>\
       <input type=radio id='ChoixRess2' name='ChoixRess' value='rec2' style='visibility:hidden'><img src='"+IMGwood30+"' onclick=document.getElementById('ChoixRess2').checked=true;Ksestimeres(); height=20 title='"+culang.transportWoodNote+"'>\
       <input type=radio id='ChoixRess3' name='ChoixRess' value='rec3' style='visibility:hidden'><img src='"+IMGstone30+"' onclick=document.getElementById('ChoixRess3').checked=true;Ksestimeres(); height=20 title='"+culang.transportStoneNote+"'>\
       <input type=radio id='ChoixRess4' name='ChoixRess' value='rec4' style='visibility:hidden'><img src='"+IMGiron30+"' onclick=document.getElementById('ChoixRess4').checked=true;Ksestimeres(); height=20 title='"+culang.transportIronNote+"'>\
       <input type=radio id='ChoixRess5' name='ChoixRess' value='rec5' style='visibility:hidden'><img src='"+IMGastone30+"' onclick=document.getElementById('ChoixRess5').checked=true;Ksestimeres(); height=20 title='"+culang.transportAheterstoneNote+"'>\
       </td></tr>\
       <tr><td colspan=2><b>"+culang.transportAmount+"</b> <span id=KsEstimationR></td></tr>\
       </table><div class='pdxStat'>"+culang.transportStatsHead+"</div><div id='statpourTr'></div>";
            t.TransportDiv.innerHTML = m;
            t.destinationCityx = document.getElementById ('typetrpx');
            t.destinationCityy = document.getElementById ('typetrpy');

            t.destinationCityx.addEventListener ('change', t.estimerRes, false);
            t.destinationCityy.addEventListener ('change', t.estimerRes, false);
            document.getElementById ('ChoixRess0').addEventListener ('click', t.estimerRes, false);
            document.getElementById ('ChoixRess1').addEventListener ('click', t.estimerRes, false);
            document.getElementById ('ChoixRess2').addEventListener ('click', t.estimerRes, false);
            document.getElementById ('ChoixRess3').addEventListener ('click', t.estimerRes, false);
            document.getElementById ('ChoixRess4').addEventListener ('click', t.estimerRes, false);
            document.getElementById ('ChoixRess5').addEventListener ('click', t.estimerRes, false);
            t.listeFavoris = document.getElementById ('KslisteFavori');
            t.estimationRes = document.getElementById ('KsEstimationR');
            t.chargelistelieux = document.getElementById ('chargelistelieux');
            t.chargelistelieux.addEventListener ('click', t.chercherFavoris, false);
            t.listeFavoris.addEventListener ('change', t.SelectFavoris, false);
            var dcp1 = new CdispCityPicker ('ptspeed1', ById('desptspeedcity'), false, t.clickCityDestinationSelect, 1);
            t.TTbutTransport = document.getElementById ('ptttButTransport');
            t.TTbutTransport.addEventListener ('click', t.clickTransportDo, false);
            t.divTranportStatus = document.getElementById ('ptTranportStatus');
            t.statpourTr = document.getElementById ('statpourTr');
            t.typetrp = document.getElementById ('typetrp');
            t.typetrp.addEventListener ('click', t.estimerRes, false);
            t.trswagmax = document.getElementById ('trswagmax');
            t.trswagmax.addEventListener ('click', t.clickUniteMax, false);
            t.Choixnbwagon  = document.getElementById ('Choixnbwagon');
            t.Choixnbwagon.addEventListener ('keyup', t.verifierWagons, false);
            var dcp0 = new CdispCityPicker ('ptspeed0', ById('srcptspeedcity'), false, t.clickCitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
            t.state = 1;
        }
        if (t.state == 1) {
            if (document.getElementById ('maparea_map').style.display!="none") {
                t.destinationCityx.value = document.getElementById ('mapXCoor').value;
                t.destinationCityy.value = document.getElementById ('mapYCoor').value;
                t.destinationCityx.style.backgroundColor="#FF9999";
                t.destinationCityy.style.backgroundColor="#FF9999";
                setTimeout(function() {
                    t.destinationCityx.style.backgroundColor="#fff";
                    t.destinationCityy.style.backgroundColor="#fff";
                }, 3000);

            }
            t.state = 2;
        }
        rows=[];
        rows[0]=[];
        m = "<TABLE class=pdxTabLined cellspacing=0><TR valign=top align=right><TD width=65></td><TD width=88 style='background: #ffc'><B>"+culang.mainHTotal+"</b></td>";
        for(i=0; i<Cities.numCities; i++)
            m += '<TD width=81><B>'+ Cities.cities[i].name.substring(0,10) +'</b></td>';
        for(i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
            rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
        }
        for (r=1; r<6; r++){
            rows[r] = [];
            for(i=0; i<Cities.numCities; i++) {
                cityID = 'city'+ Cities.cities[i].id;
                if (r==5)
                    rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
                else
                    rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
            }
        }
        m += _row ('<img height=20 src="'+IMGgold30+'">', rows[0]);
        m += _row ('<img height=20 src="'+IMGfood30+'">', rows[1]);
        m += _row ('<img height=20 src="'+IMGwood30+'">', rows[2]);
        m += _row ('<img height=20 src="'+IMGstone30+'">', rows[3]);
        m += _row ('<img height=20 src="'+IMGiron30+'">', rows[4]);
        m += _row ('<img height=20 src="'+IMGastone30+'">', rows[5]);
        m += '<TR><TD><font size=1><BR></td></tr>';
        row = [];
        var totalbouffe = 0;
        var MaxUpkeep = uW.cm.thronestats.boosts.Upkeep.Max;
        var TR = Math.min(uW.cm.ThroneController.effectBonus(79), MaxUpkeep) / 100;
    
        for(i=0; i<Cities.numCities; i++) {
            var rp = getResourceProduction (Cities.cities[i].id);
            var usage = parseIntNan(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
            usage = Math.floor(usage - (usage * TR));
            row[i] = rp[1] - usage;
        }
        m += _row (''+culang.overviewSProduce+'', row, false,  0);
        for(i=0; i<Cities.numCities; i++) {
            if (row[i] >= 0)
                row[i] = '----';
            else {
                var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-row[i]) * 3600;
                if (timeLeft > 86313600)
                    row[i] = '----';
                else {
                    if (Options.enableFoodWarn && timeLeft<(Options.foodWarnHours*3600))
                        row[i] = '<SPAN class=whiteOnRed>'+ timestrShort(timeLeft) +'</span>';
                    else
                        row[i] = timestrShort(timeLeft);
                }
            }
        }
        m += _row (''+culang.overviewFoodLeft+'', row, true, 0);
        m += '<TR><TD><font size=1><BR></td></tr>';
        for (r=1; r<14; r++){
            rows[r] = [];
            for(i=0; i<Cities.numCities; i++) {
                cityID = 'city'+ Cities.cities[i].id;
                rows[r][i] = parseInt(Seed.units[cityID]['unt'+r]);
            }
        }
        m += _row ('<img height=20 title="'+unsafeWindow.unitcost['unt1'][0]+'" src="'+IMGmiddleSupplyTroop+'">', rows[1]);
        m += _row ('<img height=20 title="'+unsafeWindow.unitcost['unt7'][0]+'" src="'+IMGmiddleCavalry+'">', rows[7]);
        m += _row ('<img height=20 title="'+unsafeWindow.unitcost['unt8'][0]+'" src="'+IMGmiddleHeavyCavalry+'">', rows[8]);
        m += _row ('<img height=20 title="'+unsafeWindow.unitcost['unt9'][0]+'" src="'+IMGmiddleSupplyWagon+'">', rows[9]);
        row = [];
        for(i=0; i<Cities.numCities; i++) {
            var RInfo = getRallypointInfo(Cities.cities[i].id);
            row[i] = '<SPAN><B>'+ RInfo.usedSlots +'/'+ RInfo.maxMarches +'</b></span>';
        }
        m += _row (''+culang.mainSRallyPoint+'', row, true, 0);   m += "</table>";
        t.statpourTr.innerHTML = m;
        clearTimeout (t.displayTimer);
        t.displayTimer = setTimeout (t.showManuel, 4000);
    },

    SelectFavoris:function() {
        var t = Tabs.Transport;
        if (t.listeFavoris.value!='') {
            var valeur=t.listeFavoris.value;
            var x=valeur.substr(0, valeur.lastIndexOf(','));
            var y=valeur.substr(valeur.lastIndexOf(',')+1, valeur.length);
            t.destinationCityx.value = x;
            t.destinationCityy.value = y;
        }
        t.estimerRes();
    },

    chercherFavoris: function() {
        var t = Tabs.Transport;
        var myA = getMyAlliance ();
        if (myA[0]!=0) {
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.perPage = 100;
            params.allianceId = myA[0];
            params.type = 'might';
            params.page = 1;
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    if (rslt.ok){
                        var z=0;
                        var m="";
                        for (var i=0; i<rslt.results.length; i++){
                            p = rslt.results[i];
                            if (p.userId != 0){
                                for (var c=0; c<p.cities.length; c++){
                                    if (Seed.player.name!=p.displayName) {
                                        m += "<option value='" + p.cities[c].xCoord + ","+ p.cities[c].yCoord+"'>" + p.displayName + " - "+unsafeWindow.g_js_strings.commonstr.city+" " + (c+1) + " - " + p.cities[c].xCoord + "," + p.cities[c].yCoord+"</option>";
                                    }
                                }
                            }
                        }
                        t.listeFavoris.innerHTML="<option value=''>-- "+culang.mainSelect+" --</option>"+m;
                    }
                },
                onFailure: function (rslt) {
                    t.listeFavoris.innerHTML="<option>"+culang.mainError+"</option>";
                },
            });
        } else {
            t.listeFavoris.innerHTML="<option>"+culang.transportNoAlliance+"</option>";
        }
    },
    verifierWagons: function() {
        var t = Tabs.Transport;
        var maxw=parseInt(rows[t.typetrp.value][t.sourceCity.idx]);
        var saisw=parseInt(t.Choixnbwagon.value);
        if (saisw > maxw) {
            t.Choixnbwagon.value=maxw;
            t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatus+'  '+maxw+' '+culang.transportStatus2+'</font>';
        }
        t.estimerRes();
    },
    estimerRes: function() {
        var t = Tabs.Transport;
        var cityID = 'city'+ t.sourceCity.id,ic=0,resact=0,ic_ty="gold",ic_text=" "+uW.g_js_strings.commonstr.gold;
        if (ById("ChoixRess1").checked) { ic_ty="rec1";ic=1;ic_text=" "+uW.g_js_strings.commonstr.food; }
        if (ById("ChoixRess2").checked) { ic_ty="rec2";ic=2;ic_text=" "+uW.g_js_strings.commonstr.wood; }
        if (ById("ChoixRess3").checked) { ic_ty="rec3";ic=3;ic_text=" "+uW.g_js_strings.commonstr.stone; }
        if (ById("ChoixRess4").checked) { ic_ty="rec4";ic=4;ic_text=" "+uW.g_js_strings.commonstr.ore; }
        if (ById("ChoixRess5").checked) { ic_ty="rec5";ic=5;ic_text=" "+uW.g_js_strings.commonstr.aetherstone; }
        if (ById("ChoixRess0").checked) { ic_ty="gold";ic=0;ic_text=" "+uW.g_js_strings.commonstr.gold; }
        var esti = 0;

        var total_units=t.Choixnbwagon.value;
        var untid=t.typetrp.value;
        var techLoadBoost = parseInt(Seed.tech.tch10)*0.1;
        var loadEffectBoost = 0;
        if (Seed.playerEffects.loadExpire > uW.unixtime()) loadEffectBoost = 25;
        var loadBoost = uW.cm.ThroneController.effectBonus(6) + loadEffectBoost;
        if (uW.cm.unitFrontendType[untid]=="siege") {
            if (untid != 9) loadBoost += uW.cm.ThroneController.effectBonus(59);
        } else {
            if (uW.cm.unitFrontendType[untid]=="horsed") {
                loadBoost += uW.cm.ThroneController.effectBonus(48);
            }
        }
        if (loadBoost > 500) {
            loadBoost = 5;
        } else {
            loadBoost = loadBoost * 0.01;
        }
        var esti = parseInt(total_units*parseInt(uW.unitstats["unt"+untid][5]) * (1 + loadBoost + techLoadBoost));

        if (ic==5) {esti = parseInt(esti / 5);}
        var x1 = parseInt(t.sourceCity.x);
        var x2 = parseInt(t.destinationCityx.value);
        var y1 = parseInt(t.sourceCity.y);
        var y2 = parseInt(t.destinationCityy.value);
        var dist = distance (x1, y1, x2, y2);
        var m = estETA(dist,ById('typetrp').value,t.sourceCity.id,1);
        var a="";
        switch(ic){
            case 0:a=unsafeWindow.g_js_strings.commonstr.gold;break;
            case 1:a=unsafeWindow.g_js_strings.commonstr.food;break;
            case 2:a=unsafeWindow.g_js_strings.commonstr.wood;break;
            case 3:a=unsafeWindow.g_js_strings.commonstr.stone;break;
            case 4:a=unsafeWindow.g_js_strings.commonstr.ore;break;
            case 5:a=unsafeWindow.g_js_strings.commonstr.aetherstone;break;
        }
        t.estimationRes.innerHTML = "<span class='boldRed'>" + addCommas(esti) + " <u>"+a+"</u></span>";
        t.estimationRes.innerHTML += "<br><b>"+culang.transportMarchTime+"</b> <span class='boldRed'>" + m.friendEtaStr + "</span>" ;

        if (ic==5)
            resact = parseIntNan(Seed.resources[cityID][ic_ty][0]);
        else {
            if (ic==0)
                resact = parseIntNan(Seed.citystats[cityID].gold[0]);
            else
                resact = parseIntNan(Seed.resources[cityID][ic_ty][0] / 3600);
        }

        if (resact < esti) {

            var untid=t.typetrp.value;
            var techLoadBoost = parseInt(Seed.tech.tch10)*0.1;
            var loadEffectBoost = 0;
            if (Seed.playerEffects.loadExpire > uW.unixtime()) loadEffectBoost = 25;
            var loadBoost = uW.cm.ThroneController.effectBonus(6) + loadEffectBoost;
            if (uW.cm.unitFrontendType[untid]=="siege") {
                if (untid != 9) loadBoost += uW.cm.ThroneController.effectBonus(59);
            } else {
                if (uW.cm.unitFrontendType[untid]=="horsed") {
                    loadBoost += uW.cm.ThroneController.effectBonus(48);
                }
            }
            if (loadBoost > 500) {
                loadBoost = 5;
            } else {
                loadBoost = loadBoost * 0.01;
            }
            var nbparunit = parseInt(parseInt(uW.unitstats["unt"+untid][5]) * (1 + loadBoost + techLoadBoost));
            if (ic==5) nbparunit=nbparunit/5;
            var uniteness = Math.floor(resact / nbparunit);
            if (uniteness<1) uniteness=0;
            t.Choixnbwagon.value = uniteness;
            t.TTbutTransport.disabled = false;
            t.estimerRes();
        }
    },
    clickUniteMax: function() {
        var t = Tabs.Transport;
        var maxw=parseInt(rows[t.typetrp.value][t.sourceCity.idx]);
        var RInfo = getRallypointInfo(t.sourceCity.id);
        if (maxw>RInfo.maxMarchSize) maxw=RInfo.maxMarchSize;
        t.Choixnbwagon.value=maxw;
        t.estimerRes();
    },
    clickTransportDo: function() {
        var t = Tabs.Transport;
        var SourceId = t.sourceCity.id;
        var DestinationId = t.destinationCity.id;
        if (!ById("ChoixRess0").checked && !ById("ChoixRess1").checked && !ById("ChoixRess2").checked && !ById("ChoixRess3").checked && !ById("ChoixRess4").checked && !ById("ChoixRess5").checked) {
            t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatusRes+'</font>';
            return;
        }
        if (t.sourceCity.x==t.destinationCityx.value && t.sourceCity.y==t.destinationCityy.value) {
            t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatusNotPossible+'</font>';
            return;
        }
        if (parseInt(t.Choixnbwagon.value)=="0") {
            t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatusNoTroops+'</font>';
            return;
        }
        var x=t.destinationCityx.value;
        var y=t.destinationCityy.value;
        if (x == 0 && y == 0) {
            t.divTranportStatus.innerHTML = '<FONT COLOR=#550000>'+culang.transportStatusCoord00+'</font>';
            return;
        }
        t.TTbutTransport.disabled=true;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.kid = 0;
        params.cid= t.sourceCity.id;
        params.type = "1";
        params.xcoord = x;
        params.ycoord = y;
        params.r1 = 0;
        params.r2 = 0;
        params.r3 = 0;
        params.r4 = 0;
        params.r5 = 0;
        params.gold = 0;
        params.u9 = 0;
        var untid=t.typetrp.value
        var techLoadBoost = parseInt(Seed.tech.tch10)*0.1;
        var loadEffectBoost = 0;
        if (Seed.playerEffects.loadExpire > uW.unixtime()) loadEffectBoost = 25;
        var loadBoost = uW.cm.ThroneController.effectBonus(6) + loadEffectBoost;
        if (uW.cm.unitFrontendType[untid]=="siege") {
            if (untid != 9) loadBoost += uW.cm.ThroneController.effectBonus(59);
        } else {
            if (uW.cm.unitFrontendType[untid]=="horsed") {
                loadBoost += uW.cm.ThroneController.effectBonus(48);
            }
        }
        if (loadBoost > 500) {
            loadBoost = 5;
        } else {
            loadBoost = loadBoost * 0.01;
        }
        var esti = parseInt(t.Choixnbwagon.value * parseInt(uW.unitstats["unt"+untid][5]) * (1 + loadBoost + techLoadBoost));        
        
        if (ById("ChoixRess5").checked) {
            esti = parseInt(esti / 5);
        }
        if (ById("ChoixRess0").checked) { params.gold = esti; }
        if (ById("ChoixRess1").checked) { params.r1 = esti; }
        if (ById("ChoixRess2").checked) { params.r2 = esti; }
        if (ById("ChoixRess3").checked) { params.r3 = esti; }
        if (ById("ChoixRess4").checked) { params.r4 = esti; }
        if (ById("ChoixRess5").checked) { params.r5 = esti; }
        if (t.typetrp.value==1)  params.u1 = t.Choixnbwagon.value;
        if (t.typetrp.value==9)  params.u9 = t.Choixnbwagon.value;
        if (t.typetrp.value==7)  params.u7 = t.Choixnbwagon.value;
        if (t.typetrp.value==8)  params.u8 = t.Choixnbwagon.value;

        t.divTranportStatus.innerHTML = "<i><b>"+culang.transportLoading+"</b></i>";
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var t = Tabs.Transport;
                var rslt = transport;
                if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unsafeWindow.unixtime();
                    var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                    for(i = 0; i <= unitsarr.length; i++){
                        if(params["u"+i]){
                            unitsarr[i] = params["u"+i];
                        }
                    }
                    var resources=new Array();
                    resources[0] = params.gold;
                    for(i=1; i<=4; i++){
                        resources[i] = params["r"+i];
                    }
                    var currentcityid =  t.sourceCity.id;
                    unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                    unsafeWindow.update_seed(rslt.updateSeed)
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                    t.divTranportStatus.innerHTML = "<font size='3px'><i><b>"+culang.transportOK+"</b></i></font>";
                    t.TTbutTransport.disabled=false;
                } else {
                    t.divTranportStatus.innerHTML ="<font color=red size='3px'><i><b>"+culang.transportMiss+"</b></i></font>";
                    if (rslt.msg) {
                        t.divTranportStatus.innerHTML +="<br><font color=black size='2px'>" + rslt.msg +"</font>";
                        t.TTbutTransport.disabled=false;
                    } else {
                        t.divTranportStatus.innerHTML +="<br><i><b>"+culang.transportStartIn2Seconds+"</b></i></font>";
                        setTimeout(function() { t.clickTransportDo(); }, 2000);
                    }
                }
            },
            onFailure: function (rslt) {
                var t = Tabs.Transport;
                if (rslt.user_action) {
                    t.divTranportStatus.innerHTML ="<font color=red size='3px'><i><b>"+culang.movementCaptchaAlert+"</b></i></font>";
                } else {

                    t.divTranportStatus.innerHTML ="<font color=red size='3px'><i><b>"+culang.transportMiss+"</b></i></font>";
                }
                t.TTbutTransport.disabled=false;
            }
        });
    },
    clickCitySourceSelect : function (city){
        var t = Tabs.Transport;
        t.sourceCity = city;
        t.TTbutTransport.disabled=false;
        var maxw=parseInt(rows[t.typetrp.value][t.sourceCity.idx]);
        var saisw=parseInt(t.Choixnbwagon.value);
        if (saisw > maxw)  t.Choixnbwagon.value=maxw;
        t.estimerRes();
    },
    clickCityDestinationSelect : function (city){
        var t = Tabs.Transport;
        t.destinationCity = city;
        t.destinationCityx.value=t.destinationCity.x;
        t.destinationCityy.value=t.destinationCity.y;
        t.TTbutTransport.disabled=false;
        t.estimerRes();
    },

}
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Reassign.js">
/************************************************************************************
 *                        KOC POWER - TABS REASSIGN                                    *
 ************************************************************************************/
var troops = {
    1: 'SupplyTroops',
    2: 'Militiaman',
    3: 'Scout',
    4: 'Pikeman',
    5: 'Swordsman',
    6: 'Archer',
    7: 'Cavalry',
    8: 'HeavyCavalry',
    9: 'SupplyWagon',
    10: 'Ballista',
    11: 'BatteringRam',
    12: 'Catapult',
    13: 'BloodThom',
    14: 'Executioner',
    15: 'SiegeWall',
};
Tabs.Reassign = {
    tabOrder: TabOptions.toReassign,
    tabLabel: culang.tabLabelReassign,
    cont: null,
    displayTimer: null,
    state: null,
    curTabBut: null,
    curTabName: null,
    sourceCity: {},
    destinationCity: {},
    rows: [],
    timer: null,
    reassignState: [],
    lRE: [],
    reassignRoutes: [],
    rallypointlevel: null,
    count: 0,
    check: false,

    show: function () {},
    hide: function () {
        var t = Tabs.Reassign;
        t.state = null;
        clearTimeout(t.displayTimer);
        clearTimeout(t.timer);
    },
    init: function (div) {
        var t = Tabs.Reassign;
        t.cont = div;
        t.reassignState = {
            running: false,
        };
        t.readReassignState();
        t.readReassignRoutes();
        t.e_reassignRoutes();
        window.addEventListener('unload', t.onUnload, false);
        t.cont = div;
        t.cont.innerHTML = '<TABLE class=pdxTab align=center><TR><TD><INPUT class=ksMSubtab ID=BoReeSubM type=submit value="' + culang.reassignTabLabel + '"></td>\
             <TD><INPUT class=ksMSubtab ID=BoReeSubA type=submit  value="' + culang.reassignAutoTabLabel + '"></td></tr></table>\
         <DIV id="BoReeOutput" style="margin-top:5px; background-color:white; max-height:' + (Options.HauteurBoite - 65) + 'px;overflow-y:auto"></div>';
        t.ReassignDiv = ById('BoReeOutput');
        ById('BoReeSubA').addEventListener('click', e_butSubtab, false);
        ById('BoReeSubM').addEventListener('click', e_butSubtab, false);
        changeSubtab(ById('BoReeSubM'));

        function e_butSubtab(evt) {
            changeSubtab(evt.target);
        }

        function changeSubtab(but) {
            if (but == t.curTabBut) return;
            if (t.curTabBut) {
                t.curTabBut.className = 'ksMSubtab';
                t.curTabBut.disabled = false;
            }
            t.curTabBut = but;
            but.className = 'ksMSubtab ksMSubtabSel';
            but.disabled = true;
            t.curTabName = but.id.substr(8);
            t.show2();
        }

    },
    show2: function () {
        var t = Tabs.Reassign;
        t.state = null;
        clearTimeout(t.displayTimer);
        if (t.curTabName == 'M') t.showManuel();
        else t.showAuto();
    },

    showAuto: function () {
        var t = Tabs.Reassign;
        clearTimeout(t.timer);
        if (t.state == null) {

            t.state = 1;

            var m = '<DIV id=pbReMainDivF class=pdxStat>' + culang.reassignAutoHead + '</div><TABLE id=pbtraderfunctions width=100% height=0% class=pdxTab><TR align="center">';
            m += '<TD><b>' + culang.mainIntervall + '</b>: <INPUT id=pbreassigninterval type=text size=2 value="' + Options.reassigninterval + '"\> ' + culang.mainMinutes + '</td>';
            m += '<TD><INPUT id=autofilloff type=checkbox unchecked=true\> <span title="' + culang.reassignAutoTroopLockNote + '">' + culang.reassignAutoTroopLock + '</span></td>';
            m += '<TD><INPUT id=pbReassShowRoutes type=submit value="' + culang.mainShowRoutes + '"></td>';
            if (t.reassignState.running == false) {
                m += '<TD><INPUT id=pbReassignState type=submit value="' + culang.mainReassign + '  = ' + culang.buttonOFF + ' "></td>';
            } else {
                m += '<TD><INPUT id=pbReassignState type=submit value="' + culang.mainReassign + '  = ' + culang.buttonON + ' "></td>';
            }

            m += '</tr></table></div>';
            m += '<DIV id=pbReassignDivD class=pdxStat>' + culang.reassignAutoHeadAddRoute + '</div>';

            m += '<TABLE id=pbaddreasignroute width=95% height=0% class=pdxTab><TR align="left">';
            m += '<TD width=20px><b>' + culang.mainCastle + '</b>:</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptassigncity></span></div></td></tr>';

            m += '<TR align="left">';
            m += '<TD width=20px><b>' + culang.mainTarget + '</b>:</td> <TD width=310px><DIV style="margin-bottom:10px;"><span id=ptassigncityTo></span></div></td>';

            m += '</table>';
            m += '<TABLE width=100% class=pdxTab><TR align="center">';
            m += '<TR><TD rowspan="2" width=50><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_1_50_s34.jpg"></td>';
            m += '<TD>' + uW.unitcost['unt1'][0] + '</td>'
            m += '<TD rowspan="2" width=50><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt2'][0] + '</td>'
            m += '<TD rowspan="2" width=50><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt3'][0] + '</td>'
            m += '<TD rowspan="2" width=50><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt4'][0] + '</td></tr>'
            m += '<TR><TD><INPUT id=pbSupplyTroops type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetSupplyTroops disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbMilitiaman type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetMilitiaman disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbScout type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetScout disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbPikeman type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetPikeman disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
            m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_50_s34.jpg"></td>';
            m += '<TD>' + uW.unitcost['unt5'][0] + '</td>'
            m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt6'][0] + '</td>'
            m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_7_50_s34.jpg"></td>'
            m += '<TD>' + unsafeWindow.unitcost['unt7'][0] + '</td>'
            m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_8_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt8'][0] + '</td></tr>'
            m += '<TR><TD><INPUT id=pbSwordsman type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetSwordsman disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbArcher type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetArcher disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbCavalry type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetCavalry disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbHeavyCavalry type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetHeavyCavalry disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
            m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_50_s34.jpg"></td>';
            m += '<TD>' + uW.unitcost['unt9'][0] + '</td>'
            m += '<TD rowspan="2"><img src="http://0cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt10'][0] + '</td>'
            m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt11'][0] + '</td>'
            m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt12'][0] + '</td>'

            m += '</tr><TR><TD><INPUT id=pbSupplyWagon type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetSupplyWagon disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbBallista type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetBallista disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbBatteringRam type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetBatteringRam disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbCatapult type=checkbox unchecked=true\>';
            m += '<INPUT id=pbtargetCatapult disabled=true type=text size=10 maxlength=10 value="0"\></td></tr>';
            
            m += '<tr><TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_13_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt13'][0] + '</td>';
            m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_14_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt14'][0] + '</td>';
            m += '<TD rowspan="2"><img src="https://kabam1-a.akamaihd.net/silooneofcamelot/fb/e2/src/img/units/unit_15_50_s34.jpg"></td>'
            m += '<TD>' + uW.unitcost['unt15'][0] + '</td>';
            m += '</tr>';
            m += '<tr><TD><INPUT id=pbBloodThom type=checkbox unchecked=true\><INPUT id=pbtargetBloodThom disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbExecutioner type=checkbox unchecked=true\><INPUT id=pbtargetExecutioner disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '<TD><INPUT id=pbSiegeWall type=checkbox unchecked=true\><INPUT id=pbtargetSiegeWall disabled=true type=text size=10 maxlength=10 value="0"\></td>';
            m += '</tr></table>';
            m += '<DIV style="text-align:center; margin-top:15px"><INPUT id=pbSaveRouteReassign type=submit value="' + culang.reassignAutoAddRoute + '"></div>';

            t.ReassignDiv.innerHTML = m;

            t.tcp = new CdispCityPicker('ptreassign', ById('ptassigncity'), true, null, 0);
            t.tcpto = new CdispCityPicker('ptreassignTo', ById('ptassigncityTo'), true);
            for (var k in troops) {
                ById('pbtarget' + troops[k]).value = parseIntNan(Seed.units['city' + t.tcp.city.id]['unt' + k]);
            }

            ById('ptassigncity').addEventListener('click', function () {
                if (ById('autofilloff').checked == false) 
                    for (var k in troops)
                        ById('pbtarget' + troops[k]).value = parseInt(Seed.units['city' + t.tcp.city.id]['unt' + k]);
            }, false);

            ById('pbReassignState').addEventListener('click', function () {
                t.toggleReassignState(this);
            }, false);
            ById('pbSaveRouteReassign').addEventListener('click', function () {
                t.addReassignRoute();
            }, false);
            ById('pbReassShowRoutes').addEventListener('click', function () {
                t.showReassignRoutes();
            }, false);

            ById('pbreassigninterval').addEventListener('keyup', function () {
                if (isNaN(ById('pbreassigninterval').value)) {
                    ById('pbreassigninterval').value = 0;
                }
                Options.reassigninterval = ById('pbreassigninterval').value;
                saveOptions();
            }, false);

            ById('pbtargetSupplyTroops').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetSupplyTroops').value)) ById('pbtargetSupplyTroops').value = 0;
            }, false);
            ById('pbtargetMilitiaman').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetMilitiaman').value)) ById('pbtargetMilitiaman').value = 0;
            }, false);
            ById('pbtargetScout').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetScout').value)) ById('pbtargetScout').value = 0;
            }, false);
            ById('pbtargetPikeman').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetPikeman').value)) ById('pbtargetPikeman').value = 0;
            }, false);
            ById('pbtargetSwordsman').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetSwordsman').value)) ById('pbtargetSwordsman').value = 0;
            }, false);
            ById('pbtargetArcher').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetArcher').value)) ById('pbtargetArcher').value = 0;
            }, false);
            ById('pbtargetCavalry').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetCavalry').value)) ById('pbtargetCavalry').value = 0;
            }, false);
            ById('pbtargetHeavyCavalry').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetHeavyCavalry').value)) ById('pbtargetHeavyCavalry').value = 0;
            }, false);
            ById('pbtargetSupplyWagon').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetSupplyWagon').value)) ById('pbtargetSupplyWagon').value = 0;
            }, false);
            ById('pbtargetBallista').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetBallista').value)) ById('pbtargetBallista').value = 0;
            }, false);
            ById('pbtargetBatteringRam').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetBatteringRam').value)) ById('pbtargetBatteringRam').value = 0;
            }, false);
            ById('pbtargetCatapult').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetCatapult').value)) ById('pbtargetCatapult').value = 0;
            }, false);
            ById('pbtargetBloodThom').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetBloodThom').value)) ById('pbtargetBloodThom').value = 0;
            }, false);
            ById('pbtargetExecutioner').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetExecutioner').value)) ById('pbtargetExecutioner').value = 0;
            }, false);
            ById('pbtargetSiegeWall').addEventListener('keyup', function () {
                if (isNaN(ById('pbtargetSiegeWall').value)) ById('pbtargetSiegeWall').value = 0;
            }, false);

            ById('pbSupplyTroops').addEventListener('click', function () {
                if (ById('pbSupplyTroops').checked == false) {
                    ById('pbtargetSupplyTroops').disabled = true;
                } else {
                    ById('pbtargetSupplyTroops').disabled = false;
                }
            }, false);
            ById('pbMilitiaman').addEventListener('click', function () {
                if (ById('pbMilitiaman').checked == false) {
                    ById('pbtargetMilitiaman').disabled = true;
                } else {
                    ById('pbtargetMilitiaman').disabled = false;
                }
            }, false);
            ById('pbScout').addEventListener('click', function () {
                if (ById('pbScout').checked == false) {
                    ById('pbtargetScout').disabled = true;
                } else {
                    ById('pbtargetScout').disabled = false;
                }
            }, false);
            ById('pbPikeman').addEventListener('click', function () {
                if (ById('pbPikeman').checked == false) {
                    ById('pbtargetPikeman').disabled = true;
                } else {
                    ById('pbtargetPikeman').disabled = false;
                }
            }, false);
            ById('pbSwordsman').addEventListener('click', function () {
                if (ById('pbSwordsman').checked == false) {
                    ById('pbtargetSwordsman').disabled = true;
                } else {
                    ById('pbtargetSwordsman').disabled = false;
                }
            }, false);
            ById('pbArcher').addEventListener('click', function () {
                if (ById('pbArcher').checked == false) {
                    ById('pbtargetArcher').disabled = true;
                } else {
                    ById('pbtargetArcher').disabled = false;
                }
            }, false);
            ById('pbCavalry').addEventListener('click', function () {
                if (ById('pbCavalry').checked == false) {
                    ById('pbtargetCavalry').disabled = true;
                } else {
                    ById('pbtargetCavalry').disabled = false;
                }
            }, false);
            ById('pbHeavyCavalry').addEventListener('click', function () {
                if (ById('pbHeavyCavalry').checked == false) {
                    ById('pbtargetHeavyCavalry').disabled = true;
                } else {
                    ById('pbtargetHeavyCavalry').disabled = false;
                }
            }, false);
            ById('pbSupplyWagon').addEventListener('click', function () {
                if (ById('pbSupplyWagon').checked == false) {
                    ById('pbtargetSupplyWagon').disabled = true;
                } else {
                    ById('pbtargetSupplyWagon').disabled = false;
                }
            }, false);
            ById('pbBallista').addEventListener('click', function () {
                if (ById('pbBallista').checked == false) {
                    ById('pbtargetBallista').disabled = true;
                } else {
                    ById('pbtargetBallista').disabled = false;
                }
            }, false);
            ById('pbBatteringRam').addEventListener('click', function () {
                if (ById('pbBatteringRam').checked == false) {
                    ById('pbtargetBatteringRam').disabled = true;
                } else {
                    ById('pbtargetBatteringRam').disabled = false;
                }
            }, false);
            ById('pbCatapult').addEventListener('click', function () {
                if (ById('pbCatapult').checked == false) {
                    ById('pbtargetCatapult').disabled = true;
                } else {
                    ById('pbtargetCatapult').disabled = false;
                }
            }, false);
            ById('pbBloodThom').addEventListener('click', function () {
                if (ById('pbBloodThom').checked == false) {
                    ById('pbtargetBloodThom').disabled = true;
                } else {
                    ById('pbtargetBloodThom').disabled = false;
                }
            }, false);
            ById('pbExecutioner').addEventListener('click', function () {
                if (ById('pbExecutioner').checked == false) {
                    ById('pbtargetExecutioner').disabled = true;
                } else {
                    ById('pbtargetExecutioner').disabled = false;
                }
            }, false);
            ById('pbSiegeWall').addEventListener('click', function () {
                if (ById('pbSiegeWall').checked == false) {
                    ById('pbtargetSiegeWall').disabled = true;
                } else {
                    ById('pbtargetSiegeWall').disabled = false;
                }
            }, false);
            
        } else {


        }
        t.timer = setTimeout(t.showAuto, 3000);
    },
    getRallypoint: function (cityId) {
        var t = Tabs.Reassign;
        for (var o in Seed.buildings[cityId]) {
            var buildingType = parseInt(Seed.buildings[cityId][o][0]);
            var buildingLevel = parseInt(Seed.buildings[cityId][o][1]);
            if (buildingType == 12) {
                t.rallypointlevel = parseInt(buildingLevel);
                if (uW.cm.PrestigeModel.isPrestige(cityId)) {
                    var a = uW.cm.PrestigeModel.getPrestigeLevel(cityId);
                    if (a > 0) {
                        var mm = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
                            k = uW.JSON.parse(mm),
                            o = k.values[a - 1][2],
                            ii = parseFloat(o);
                        t.rallypointlevel = t.rallypointlevel + ii;
                    }
                }
            }
        }
    },

    e_reassignRoutes: function () {
        var t = Tabs.Reassign;
        var now = new Date();
        if (t.reassignState.running == true) {
            var now = new Date().getTime() / 1000.0;
            now = now.toFixed(0);
            var last = Options.lastreassign;
            if (now > (parseInt(last) + (Options.reassigninterval * 60))) {
                t.checkdoReassign();
            }
        }
        setTimeout(function () {
            t.e_reassignRoutes();
        }, Options.reassigninterval * 1000);

    },

    delReassignRoutes: function () {

        var t = Tabs.Reassign;

        t.reassignRoutes = [];

    },
    checkcoords: function (obj) {
        var t = Tabs.Reassign;
        if (obj.id == 'pbok') {
            t.check = true;
            t.addReassignRoute();
        }
        return;
    },
    addReassignRoute: function () {
        var t = Tabs.Reassign;
        var city = t.tcp.city.id;
        if (t.tcpto.city == null) return;
        if (t.tcp.city.id == t.tcpto.city.id) return;
        t.check = false;
        var SendSupplyTroop = ById('pbSupplyTroops').checked;
        var SendMilitiaman = ById('pbMilitiaman').checked;
        var SendScout = ById('pbScout').checked;
        var SendPikeman = ById('pbPikeman').checked;
        var SendSwordsman = ById('pbSwordsman').checked;
        var SendArchers = ById('pbArcher').checked;
        var SendCavalry = ById('pbCavalry').checked;
        var SendHeavyCavalry = ById('pbHeavyCavalry').checked;
        var SendSupplyWagons = ById('pbSupplyWagon').checked;
        var SendBallista = ById('pbBallista').checked;
        var SendBatteringRam = ById('pbBatteringRam').checked;
        var SendCatapult = ById('pbCatapult').checked;
        var SendBloodThom = ById('pbBloodThom').checked;
        var SendExecutioner = ById('pbExecutioner').checked;
        var SendSiegeWall = ById('pbSiegeWall').checked;
        
        var SupplyTroop = ById('pbtargetSupplyTroops').value;
        var Militiaman = ById('pbtargetMilitiaman').value;
        var Scout = ById('pbtargetScout').value;
        var Pikeman = ById('pbtargetPikeman').value;
        var Swordsman = ById('pbtargetSwordsman').value;
        var Archers = ById('pbtargetArcher').value;
        var Cavalry = ById('pbtargetCavalry').value;
        var HeavyCavalry = ById('pbtargetHeavyCavalry').value;
        var SupplyWagons = ById('pbtargetSupplyWagon').value;
        var Ballista = ById('pbtargetBallista').value;
        var BatteringRam = ById('pbtargetBatteringRam').value;
        var Catapult = ById('pbtargetCatapult').value;
        var BloodThom = ById("pbtargetBloodThom").value;
        var Executioner = ById("pbtargetExecutioner").value;
        var SiegeWall = ById("pbtargetSiegeWall").value;
        
        var target_x = t.tcpto.city.x;
        var target_y = t.tcpto.city.y;

        var lRE = t.reassignRoutes;
        lRE.push({
            city: city,
            city_to: t.tcpto.city.id,
            target_x: target_x,
            target_y: target_y,
            SendSupplyTroop: SendSupplyTroop,
            SupplyTroop: SupplyTroop,
            SendMilitiaman: SendMilitiaman,
            Militiaman: Militiaman,
            SendScout: SendScout,
            Scout: Scout,
            SendPikeman: SendPikeman,
            Pikeman: Pikeman,
            SendSwordsman: SendSwordsman,
            Swordsman: Swordsman,
            SendArchers: SendArchers,
            Archers: Archers,
            SendCavalry: SendCavalry,
            Cavalry: Cavalry,
            SendHeavyCavalry: SendHeavyCavalry,
            HeavyCavalry: HeavyCavalry,
            SendSupplyWagons: SendSupplyWagons,
            SupplyWagons: SupplyWagons,
            SendBallista: SendBallista,
            Ballista: Ballista,
            SendBatteringRam: SendBatteringRam,
            BatteringRam: BatteringRam,
            SendCatapult: SendCatapult,
            Catapult: Catapult,
            SendBloodThom: SendBloodThom,
            BloodThom: BloodThom,
            SendExecutioner: SendExecutioner,
            Executioner: Executioner,
            SendSiegeWall: SendSiegeWall,
            SiegeWall: SiegeWall,
        });
        ById('pbReassignDivD').style.background = '#99FF99';
        setTimeout(function () {
            (ById('pbReassignDivD').style.background = '');
        }, 1000);
    },
    showReassignRoutes: function () {
        var t = Tabs.Reassign;
        var popReassignRoutes = null;
        t.popReassignRoutes = new CPopup('pbShowTrade', 0, 0, 1100, 500, true, function () {
            clearTimeout(1000);
        });
        var m = '<DIV style="max-height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowReassignRoutes" id="pbRoutesQueue">';
        t.popReassignRoutes.getMainDiv().innerHTML = '</table></div>' + m;
        t.popReassignRoutes.getTopDiv().innerHTML = '<div class="popupBanner">' + culang.reassignAutoHeadRoutes + '</div>';
        t.paintReassignRoutes();
        t._addTabHeader();
        t.popReassignRoutes.show(true);
    },
    paintReassignRoutes: function () {
        var t = Tabs.Reassign;
        var r = t.reassignRoutes;
        var cityname;
        var cityto;
        for (var i = (r.length - 1); i >= 0; i--) {
            for (var y = 0; y < Seed.cities.length; y++) {
                if (parseInt(Seed.cities[y][0]) == r[i].city) var cityname = Seed.cities[y][1];
                if (r[i].city_to) 
                    if (parseInt(Seed.cities[y][0]) == r[i].city_to) var cityto = Seed.cities[y][1];
            }
            var queueId = i;
            if (!r[i].city_to) cityto = r[i].target_x + ',' + r[i].target_y;
            t._addTab(queueId, cityname, cityto, r[i].SendSupplyTroop, r[i].SupplyTroop, r[i].SendMilitiaman, r[i].Militiaman, r[i].SendScout, r[i].Scout, r[i].SendPikeman, r[i].Pikeman, r[i].SendSwordsman, r[i].Swordsman, r[i].SendArchers, r[i].Archers, r[i].SendCavalry, r[i].Cavalry, r[i].SendHeavyCavalry, r[i].HeavyCavalry, r[i].SendSupplyWagons, r[i].SupplyWagons, r[i].SendBallista, r[i].Ballista, r[i].SendBatteringRam, r[i].BatteringRam, r[i].SendCatapult, r[i].Catapult, r[i].SendBloodThom, r[i].BloodThom, r[i].SendExecutioner, r[i].Executioner, r[i].SendSiegeWall, r[i].SiegeWall);
        }
    },

    _addTab: function (queueId, cityname, cityto, SendSupplyTroop, SupplyTroop, SendMilitiaman, Militiaman, SendScout, Scout, SendPikeman, Pikeman, SendSwordsman, Swordsman, SendArchers, Archers, SendCavalry, Cavalry, SendHeavyCavalry, HeavyCavalry, SendSupplyWagons, SupplyWagons, SendBallista, Ballista, SendBatteringRam, BatteringRam, SendCatapult, Catapult, SendBloodThom, BloodThom, SendExecutioner, Executioner,SendSiegeWall, SiegeWall) {
        var t = Tabs.Reassign;
        var row = ById('pbRoutesQueue').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = queueId;
        row.insertCell(1).innerHTML = cityname;
        row.insertCell(2).innerHTML = cityto;
        row.insertCell(3).innerHTML = SendSupplyTroop;
        row.insertCell(4).innerHTML = addCommas(SupplyTroop);
        row.insertCell(5).innerHTML = SendMilitiaman;
        row.insertCell(6).innerHTML = addCommas(Militiaman);
        row.insertCell(7).innerHTML = SendScout;
        row.insertCell(8).innerHTML = addCommas(Scout);
        row.insertCell(9).innerHTML = SendPikeman;
        row.insertCell(10).innerHTML = addCommas(Pikeman);
        row.insertCell(11).innerHTML = SendSwordsman;
        row.insertCell(12).innerHTML = addCommas(Swordsman);
        row.insertCell(13).innerHTML = SendArchers;
        row.insertCell(14).innerHTML = addCommas(Archers);
        row.insertCell(15).innerHTML = SendCavalry;
        row.insertCell(16).innerHTML = addCommas(Cavalry);
        row.insertCell(17).innerHTML = SendHeavyCavalry;
        row.insertCell(18).innerHTML = addCommas(HeavyCavalry);
        row.insertCell(19).innerHTML = SendSupplyWagons;
        row.insertCell(20).innerHTML = addCommas(SupplyWagons);
        row.insertCell(21).innerHTML = SendBallista;
        row.insertCell(22).innerHTML = addCommas(Ballista);
        row.insertCell(23).innerHTML = SendBatteringRam;
        row.insertCell(24).innerHTML = addCommas(BatteringRam);
        row.insertCell(25).innerHTML = SendCatapult;
        row.insertCell(26).innerHTML = addCommas(Catapult);
        row.insertCell(27).innerHTML = SendBloodThom;
        row.insertCell(28).innerHTML = addCommas(BloodThom);
        row.insertCell(29).innerHTML = SendExecutioner;
        row.insertCell(30).innerHTML = addCommas(Executioner);
        row.insertCell(31).innerHTML = SendSiegeWall;
        row.insertCell(32).innerHTML = addCommas(SiegeWall);
        row.insertCell(33).innerHTML = '<a id="tradecancel_' + queueId + '"><span><img src="' + IMGdeleteButton + '" border=0 title="' + culang.mainDelete + '" alt="' + culang.mainDelete + '"></span></a>';
        
        ById('tradecancel_' + queueId).addEventListener('click', function () {
            t.cancelQueueElement(queueId);
        }, false);
    },

    _addTabHeader: function () {
        var t = Tabs.Reassign;
        var row = ById('pbRoutesQueue').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = "ID";
        row.insertCell(1).innerHTML = culang.reassignAutoLogOK;
        row.insertCell(2).innerHTML = culang.reassignAutoLogOK2;
        row.insertCell(3).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt1'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_1_30_s34.jpg>';
        row.insertCell(4).innerHTML = "";
        row.insertCell(5).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt2'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_2_30_s34.jpg>';
        row.insertCell(6).innerHTML = "";
        row.insertCell(7).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt3'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_3_30_s34.jpg>';
        row.insertCell(8).innerHTML = "";
        row.insertCell(9).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt4'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_4_30_s34.jpg>';
        row.insertCell(10).innerHTML = "";
        row.insertCell(11).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt5'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_5_30_s34.jpg>';
        row.insertCell(12).innerHTML = "";
        row.insertCell(13).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt6'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_6_30_s34.jpg>';
        row.insertCell(14).innerHTML = "";
        row.insertCell(15).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt7'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_7_30_s34.jpg>';
        row.insertCell(16).innerHTML = "";
        row.insertCell(17).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt8'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_8_30_s34.jpg>';
        row.insertCell(18).innerHTML = "";
        row.insertCell(19).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt9'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_9_30_s34.jpg>';
        row.insertCell(20).innerHTML = "";
        row.insertCell(21).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt10'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_10_30_s34.jpg>';
        row.insertCell(22).innerHTML = "";
        row.insertCell(23).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt11'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_11_30_s34.jpg>';
        row.insertCell(24).innerHTML = "";
        row.insertCell(25).innerHTML = '<img height=20 title="' + unsafeWindow.unitcost['unt12'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_12_30_s34.jpg>';
        row.insertCell(26).innerHTML = "";
        row.insertCell(27).innerHTML = '<img height=20 title="' + uW.unitcost['unt13'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_13_30_s34.jpg>';
        row.insertCell(28).innerHTML = "";
        row.insertCell(29).innerHTML = '<img height=20 title="' + uW.unitcost['unt14'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_14_30_s34.jpg>';
        row.insertCell(30).innerHTML = "";
        row.insertCell(31).innerHTML = '<img height=20 title="' + uW.unitcost['unt15'][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_15_30_s34.jpg>';
        row.insertCell(32).innerHTML = "";
        row.insertCell(33).innerHTML = culang.mainDelete;

    },

    cancelQueueElement: function (queueId) {
        var t = Tabs.Reassign;
        var queueId = parseInt(queueId);
        t.reassignRoutes.splice(queueId, 1);
        t.showReassignRoutes();
    },

    saveReassignRoutes: function () {
        var t = Tabs.Reassign;
        var serverID = getServerId();
        GM_setValue('reassignRoutes_' + serverID, JSON2.stringify(t.reassignRoutes));
    },
    readReassignRoutes: function () {
        var t = Tabs.Reassign;
        var serverID = getServerId();
        s = GM_getValue('reassignRoutes_' + serverID);
        if (s != null) {
            route = JSON2.parse(s);
            for (k in route)
            t.reassignRoutes[k] = route[k];
        }
    },
    saveReassignState: function () {
        var t = Tabs.Reassign;
        var serverID = getServerId();
        GM_setValue('reassignState_' + serverID, JSON2.stringify(t.reassignState));
    },
    readReassignState: function () {
        var t = Tabs.Reassign;
        var serverID = getServerId();
        s = GM_getValue('reassignState_' + serverID);
        if (s != null) {
            state = JSON2.parse(s);
            for (k in state)
            t.reassignState[k] = state[k];
        }
    },
    toggleReassignState: function (obj) {
        var t = Tabs.Reassign;
        obj = ById('pbReassignState');
        if (t.reassignState.running == true) {
            t.reassignState.running = false;
            if (obj) obj.value = culang.mainReassign + "  = " + culang.buttonOFF;
            t.checkdoreassigntimeout = null;
            t.count = 0;
            Options.lastreassign = 0;
            saveOptions();

        } else {
            t.reassignState.running = true;
            if (obj) obj.value = culang.mainReassign + " = " + culang.buttonON;
            t.e_reassignRoutes();
        }
    },

    checkdoReassign: function () {
        var t = Tabs.Reassign;
        t.doReassign(t.count);
        t.count++;
        if (t.count < t.reassignRoutes.length && t.reassignState.running) {
            t.checkdoreassigntimeout = setTimeout(function () {
                t.checkdoReassign();
            }, 5000);
        } else {
            var now = new Date().getTime() / 1000.0;
            now = now.toFixed(0);
            Options.lastreassign = now;
            saveOptions();
            t.count = 0;
        }
    },

    doReassign: function (count,tt) {
        var t = Tabs.Reassign;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if (t.reassignRoutes.length == 0) return;
        var send = [];
        var citytotal = 0;
        var totalsend = 0;
        if (tt != undefined) params.tt = tt;
        var city = t.reassignRoutes[count]["city"];
        if (t.reassignRoutes[count]["city_to"]) {
            var cityto = t.reassignRoutes[count]["city_to"];
            var xcoord = Cities.byID[cityto].x;
            var ycoord = Cities.byID[cityto].y;
        } else {
            var xcoord = t.reassignRoutes[count]["target_x"];
            var ycoord = t.reassignRoutes[count]["target_y"];        
        }
        var cityID = 'city' + city;
        if (!Cities.byID[city]) return;
        var marching = getMarchInfoBOT(cityID);
        t.getRallypoint(cityID);
        var e = 1;
        var f = uW.unixtime();
        if (Seed.playerEffects.aurasExpire) {
            if (Seed.playerEffects.aurasExpire > f) {
                e = 1.15
            }
        }
        if (Seed.playerEffects.auras2Expire) {
            if (Seed.playerEffects.auras2Expire > f) {
                e = 1.3
            }
        }
        if (uW.cm.PrestigeModel.isPrestige(city)) {
            var b = uW.cm.PrestigeModel.getPrestigeLevel(city);
            if (b > 0) {
                var r = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
                    m = uW.JSON.parse(r),
                    u = m.values[b - 1][1],
                    k = parseFloat(u);
                e *= k;
            }
        }
        var q = uW.cm.ThroneController.effectBonus(66);
        if (q > 150) q = 150;
        var niveauPointRall = parseInt(getCityBuilding(city, 12).maxLevel);
        var maxsend = parseInt(niveauPointRall * 10000 * e);
        if (niveauPointRall == 11) maxsend = parseInt(150000 * e);
        if (niveauPointRall == 12) maxsend = parseInt(200000 * e);
        maxsend = Math.round(maxsend * (1 + q / 100));
        
        totalsend = 0;
        var troopsselect = ["SupplyTroop", "Militiaman", "Scout", "Pikeman", "Swordsman", "Archers", "Cavalry", "HeavyCavalry", "SupplyWagons", "Ballista", "BatteringRam", "Catapult", "BloodThom", "Executioner", "SiegeWall"];
        try {
        for (k = 0; k < troopsselect.length; k++) {
            if (uW.unitcost['unt' + (k + 1)]) {
                var citytroops = Seed.units[cityID]['unt' + (parseInt(k) + 1)];
                var marchtroops = marching.marchUnits[parseInt(k) + 1];
                citytotal = parseInt(citytroops) + parseInt(marchtroops);
                if (t.reassignRoutes[count]['Send' + troopsselect[k]] == false) {
                    continue;
                }
                if (citytotal > t.reassignRoutes[count][troopsselect[k]]) {
                    var sendtroops = parseInt(citytotal) - parseInt(t.reassignRoutes[count][troopsselect[k]]);
                    if (parseInt(sendtroops) > parseInt(citytroops)) sendtroops = citytroops;
                    if (parseInt(sendtroops) < 0) sendtroops = 0;
                    send[(parseInt(k) + 1)] = sendtroops;
                    totalsend += parseInt(send[(parseInt(k) + 1)]);

                }
                if (totalsend > maxsend) {
                    totalsend -= send[(parseInt(k) + 1)];
                    send[(parseInt(k) + 1)] = parseInt(maxsend - totalsend);
                    totalsend += parseInt(send[(parseInt(k) + 1)]);
                    break;
                }
            } else {
                send[(parseInt(k) + 1)] = 0;
            }
        }
        } catch(ex) {
            alert(inspect(ex,5));
        }
        for (var zz = 0; zz < Seed.cities.length; zz++) {
            if (parseInt(Seed.cities[zz][0]) == city) var cityname = Seed.cities[zz][1];
        }

        params.cid = city;
        params.type = "5";
        params.kid = 0;
        params.xcoord = xcoord;
        params.ycoord = ycoord;
        params.g = 0;
        params.r1 = 0;
        params.r2 = 0;
        params.r3 = 0;
        params.r4 = 0;
        params.r5 = 0;
        for (k = 1; k <= troopsselect.length; k++) {
            if (parseIntNan(send[k]) > 0) params["u" + k] = parseIntNan(send[k]);
        }
        if (totalsend > 0) {
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                loading: true,
                onSuccess: function (transport) {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                        var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                        var ut = unixTime();
                        var unitsarr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0];
                        for (i = 0; i <= unitsarr.length; i++) {
                            if (params["u" + i]) {
                                unitsarr[i] = params["u" + i];
                            }
                        }
                        var resources = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                        var currentcityid = city;
                        unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                        if (rslt.updateSeed) {
                            unsafeWindow.update_seed(rslt.updateSeed)
                        };
                        actionLog("" + culang.mainReassign + "", "" + culang.reassignAutoLogOK + " " + cityname + " " + culang.reassignAutoLogOK2 + " " + xcoord + ',' + ycoord + "  ->   " + culang.mainTroops + ": <span class='boldRed'>" + totalsend + "</span>");
                    } else {
                        if (rslt.user_action) {
                            if (rslt.user_action == "backOffWaitTime") {
                                var t = Tabs.Reassign;
                                var tt = null;
                                if (rslt.tt) tt = rslt.tt;
                                var wait = 1;
                                if (rslt.wait_time) wait = rslt.wait_time;
                                setTimeout(function () {
                                    t.doReassign(count, tt);
                                }, wait * 1000);
                                return;
                            } else {
                                actionLog("" + culang.mainReassign + "", "<b><font color=red>alert " + rslt.user_action + " </font></b>");
                            }
                        } else {
                            actionLog("" + culang.mainReassign + "", "From: " + cityname + " to : " + xcoord + ',' + ycoord + " -> <font colr=red>" + uW.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null)) + "</font>");
                        }
                    }
                },
                onFailure: function (transport) {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.user_action) {
                        actionLog("" + culang.mainReassign + "", "<b><font color=red>" + culang.movementCaptchaAlert + "</font></b>");
                        new CdialogCancelContinue('<SPAN class=boldRed>' + culang.reassignCaptchaAlert + '</span>', null, null, mainPop.getMainDiv);
                    } else {
                        actionLog("" + culang.mainReassign + "", "<font color=red>" + transport.responseText + "</font>");

                    }
                }
            });
        }
    },
    show: function () {
        var t = Tabs.Reassign;
    },
    hide: function () {
        var t = Tabs.Reassign;
    },
    onUnload: function () {
        var t = Tabs.Reassign;
        if (!ResetAll) t.saveReassignRoutes();
        if (!ResetAll) t.saveReassignState();
    },

    showManuel: function () {
        var t = Tabs.Reassign;
        var ModelCity = {};
        var rownum = 0;
        var rownum2 = 0;

        function _row(name, row, noTotal) {
            if (rownum++ % 2) style = '';
            else style = ' style = "background: #e8e8e8"';
            var tot = 0;
            var m = [];
            m.push('<TR style="background: #fff" align=right');
            m.push(style);
            m.push('><TD');
            m.push(style);
            m.push('><B>');
            m.push(name);
            m.push('</td>');
            if (noTotal) {
                m.push('<TD');
                m.push(style);
                m.push('>&nbsp;</td>');
            } else {
                for (i = 0; i < row.length; i++)
                tot += row[i];
                m.push('<TD style="background: #ffc">');
                m.push(addCommas(tot));
                m.push('</td>');
            }
            for (i = 0; i < row.length; i++) {
                m.push('<TD');
                m.push(style);
                m.push('>');
                m.push(addCommas(row[i]));
                m.push('</td>');
            }
            m.push('</tr>');
            return m.join('');
        }
        if (t.state == null) {
            m = "<DIV class=pdxStat>" + culang.reassignHead + "</div>";
            m += "<div id='ptREAStatus' style='text-align:center;overflow-y:auto; max-height:30px; border-bottom:1px solid #141516;'></div>";
            m += "<TABLE width='95%' class=pdxTab border=0 align=left>\
        <tr align=center valign=middle><td colspan=1 width=100><b><u>" + culang.mainCastle + "</b></u><br><span id=REAsrcRptspeedcity></span></td>\
        <td colspan=1 width='100px'><input type=button style='font-weight:bold' id=REAaction value='" + culang.mainReassign + "'></td>\
        <td colspan=1 width='100px'><b><u>" + culang.mainTarget + "</b></u><br><span id=REAdesRptspeedcity></span></td><td width=150 colspan=1><b><u>" + culang.reassignEST + "</b></u><br>&nbsp;" + culang.mainDistance + ": <span id='KsEstimationREAD'>&nbsp;</span></td></tr>\
        <tr align=center valign=top><td width=100><div id=REAstatsource></div></td>\
        <td ><table cellspacing=0 cellpadding=0 width=99%>";
            for (r = 1; r < 16; r++) {
                if (rownum++ % 2) style = '';
                else style = ' style = "background: #e8e8e8"';
                m += '<tr ' + style + '><td  align=right><img height=20 title="' + unsafeWindow.unitcost['unt' + r][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_' + r + '_30_s34.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="REAnbunit' + r + '" type=text size=7 value="0"></td></tr>';
            }

            m += "</table></td><td><div id=REAstatdest></div></td>";
            m += "<td colspan=2><table cellspacing=0 cellpadding=0 width=80%>";
            rownum = 0;
            for (r = 1; r < 16; r++) {
                if (rownum++ % 2) style = '';
                else style = 'background: #e8e8e8;';
                m += '<tr style="' + style + ' height:16px;font-size:11px;"><td width=50% height=20 align=center><span id="KsEstimationREAZ' + r + '">&nbsp;</span></td></tr>';
            }
            m += "</tr></table>";
            m += "</tr><tr><td colspan=4><center><b>" + culang.mainKnights + "</b>: <SELECT id='REApiKnight' type=list></center></tr><tr><td colspan=4><div class='pdxStat'>" + culang.reassignHeadStats + "</div><div id='statpourREA'></div></td></tr></table>";
            t.ReassignDiv.innerHTML = m;
            t.statpourREA = document.getElementById('statpourREA');
            t.statutREA = document.getElementById('ptREAStatus');
            t.actionREA = document.getElementById('REAaction');
            t.actionREA.addEventListener('click', function () {t.clickReassigneDo();}, false);
            var dcp1 = new CdispCityPicker('ptREA1', ById('REAdesRptspeedcity'), false, t.clickREACityDestinationSelect, 1);
            var dcp0 = new CdispCityPicker('ptREA0', ById('REAsrcRptspeedcity'), false, t.clickREACitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
            t.state = 1;
            t.estimerTemps();
        }
        rows = [];
        rows[0] = [];
        m = "<TABLE class=ptTabLined cellspacing=0><TR valign=top align=right><TD width=20></td><TD width=88 style='background: #ffc'><B>" + culang.mainHTotal + "</b></td>";
        for (i = 0; i < Cities.numCities; i++) {
            m += '<TD width=81><B>' + Cities.cities[i].name.substring(0, 10) + '</b></td>';
        }
        for (r = 1; r < 16; r++) {
            rows[r] = [];
            for (i = 0; i < Cities.numCities; i++) {
                cityID = 'city' + Cities.cities[i].id;
                rows[r][i] = parseIntNan(Seed.units[cityID]['unt' + r]);
            }
        }
        for (r = 1; r < 16; r++) {
            m += _row('<img height=18 title="' + unsafeWindow.unitcost['unt' + r][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_' + r + '_30_s34.jpg>', rows[r]);
        }
        row = [];
        for (i = 0; i < Cities.numCities; i++) {
            var cityId = 'city' + Cities.cities[i].id;
            var slots = 0;
            for (var k in Seed.queue_atkp[cityId]) {
                march = Seed.queue_atkp[cityId][k];
                if (typeof (march) == 'object') slots++;
            }
            var niveauPointRall = parseInt(getCityBuilding(Cities.cities[i].id, 12).maxLevel);
            if (niveauPointRall == 12) niveauPointRall = 11;
            if (uW.cm.PrestigeModel.isPrestige(Cities.cities[i].id)) {
                var a = uW.cm.PrestigeModel.getPrestigeLevel(Cities.cities[i].id);
                if (a > 0) {
                    var mm = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
                        k = uW.JSON.parse(mm),
                        o = k.values[a - 1][2],
                        ii = parseFloat(o);
                    niveauPointRall = niveauPointRall + ii;
                }
            }
            row[i] = '<SPAN><B>' + slots + '/' + niveauPointRall + '</b></span>';
        }
        m += _row('' + culang.mainSRallyPoint + '', row, true, 0);
        m += "</table>";
        t.statpourREA.innerHTML = m;
        clearTimeout(t.displayTimer);
        t.displayTimer = setTimeout(t.showManuel, 4000);
    },
    estimerTemps: function () {
        var t = Tabs.Reassign;
        var x1 = parseInt(t.sourceCity.x);
        var x2 = parseInt(t.destinationCity.x);
        var y1 = parseInt(t.sourceCity.y);
        var y2 = parseInt(t.destinationCity.y);
        var dist = distance(x1, y1, x2, y2);
        ById("KsEstimationREAD").innerHTML = "<b>" + dist + "</b>";
        for (r = 1; r < 16; r++) {
            var m = estETA(dist, r, t.sourceCity.id, 5);
            ById("KsEstimationREAZ" + r).innerHTML = "<span class='boldRed'>" + m.friendEtaStr + "</span>";
        }
    },
    clickReassigneDo: function (tt) {
        var t = Tabs.Reassign;
        t.statutREA.innerHTML = '';
        var totalunit = 0;
        for (r = 1; r < 16; r++) {
            if (parseInt(ById("REAnbunit" + r).value) > parseInt(ById("REAdestunit" + r).value)) {
                ById("REAnbunit" + r).style.backgroundColor = "red";
                return false;
            }
            totalunit = totalunit + parseInt(ById("REAnbunit" + r).value);
            ById("REAnbunit" + r).style.backgroundColor = "";
        }
        if (t.sourceCity.id == t.destinationCity.id) {
            t.statutREA.innerHTML = '<FONT COLOR=#550000>' + culang.reassignSameCity + '</font>';
            return;
        }
        if (totalunit == 0) {
            t.statutREA.innerHTML = '<FONT COLOR=#550000>' + culang.reassignSelectTroops + '</font>';
            return;
        }
        var e = 1;
        var f = uW.unixtime();
        if (Seed.playerEffects.aurasExpire) {
            if (Seed.playerEffects.aurasExpire > f) {
                e = 1.15
            }
        }
        if (Seed.playerEffects.auras2Expire) {
            if (Seed.playerEffects.auras2Expire > f) {
                e = 1.3
            }
        }
        if (uW.cm.PrestigeModel.isPrestige(t.sourceCity.id)) {
            var b = uW.cm.PrestigeModel.getPrestigeLevel(t.sourceCity.id);
            if (b > 0) {
                var r = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
                    m = uW.JSON.parse(r),
                    u = m.values[b - 1][1],
                    k = parseFloat(u);
                e *= k;
            }
        }

        var q = uW.cm.ThroneController.effectBonus(66);
        if (q > 150) q = 150;
        var niveauPointRall = parseInt(getCityBuilding(t.sourceCity.id, 12).maxLevel);
        var maxtroupe = parseInt(niveauPointRall * 10000 * e);
        if (niveauPointRall == 11) maxtroupe = parseInt(150000 * e);
        if (niveauPointRall == 12) maxtroupe = parseInt(200000 * e);
        maxtroupe = Math.round(maxtroupe * (1 + q / 100));
        if (totalunit > maxtroupe) {
            t.statutREA.innerHTML = '<FONT COLOR=#550000>' + culang.reassignMaxRP + ' ' + maxtroupe + ' ' + culang.reassignMaxRP2 + '</font>';
            return;
        }

        t.actionREA.disabled = true;
        var x = t.destinationCity.x;
        var y = t.destinationCity.y;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if (tt != undefined) params.tt = tt;
        for (var i = 1; i<=15; i++) {
            if (ById("REAnbunit"+i).value > 0) {
                params['u'+i] = ById("REAnbunit"+i).value;
            }
        }
        params.cid = t.sourceCity.id;
        params.type = "5";
        params.kid = ById("REApiKnight").value;
        params.xcoord = x;
        params.ycoord = y;
        params.g = 0;
        params.r1 = 0;
        params.r2 = 0;
        params.r3 = 0;
        params.r4 = 0;
        params.r5 = 0;
        t.statutREA.innerHTML = "<font size='2px'><b><i>" + culang.reassignLoading + "</i></b></font>";
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var t = Tabs.Reassign;
                var rslt = transport;
                if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unsafeWindow.unixtime();
                    var unitsarr = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0];
                    for (i = 0; i <= unitsarr.length; i++) {
                        if (params["u" + i]) {
                            unitsarr[i] = params["u" + i];
                        }
                    }
                    var resources = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
                    var currentcityid = t.sourceCity.id;
                    unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                    if (rslt.updateSeed) {
                        unsafeWindow.update_seed(rslt.updateSeed)
                    };
                    t.clickREACitySourceSelect(t.sourceCity);
                    t.statutREA.innerHTML = "<font size='2px'><b>" + culang.reassignOK + " " + timestr(timediff) + "</font>";
                    t.actionREA.disabled = false;
                } else {
                    if (rslt.user_action == "backOffWaitTime") {
                        if (rslt.tt) var tt = rslt.tt;
                        var wait = 1;
                        if (rslt.wait_time) wait = rslt.wait_time;
                        setTimeout(function () {
                            t.clickReassigneDo(tt);
                        }, wait * 1000);
                        return;
                    }
                    t.statutREA.innerHTML = "<font color=red size='2px'>" + culang.reassignError + "</font>";
                    if (rslt.msg) {
                        t.statutREA.innerHTML += "<br><font color=black size='2px'>" + rslt.msg + "</font>";
                        t.actionREA.disabled = false;
                    } else {
                        t.statutREA.innerHTML += "<br>" + culang.reassignIn2Minutes + "</font>";
                        setTimeout(function () {
                            t.clickReassigneDo();
                        }, 2000);
                    }
                }
            },
            onFailure: function () {
                var t = Tabs.Reassign;
                t.statutREA.innerHTML = "<font color=red>" + culang.reassignError + "</font>";
                t.actionREA.disabled = false;
            }
        });
    },
    clickREACitySourceSelect: function (city) {
        var t = Tabs.Reassign;
        var rownum = 0;
        if (t.sourceCity != city) {
            t.sourceCity = city;
            for (r = 1; r < 16; r++) {
                ById("REAnbunit" + r).value = "0";
            }
        } else {
            var cityID = 'city' + t.sourceCity.id;
            for (r = 1; r < 16; r++) {
                if (parseInt(Seed.units[cityID]['unt' + r]) < ById("REAnbunit" + r).value) ById("REAnbunit" + r).value = "0";
            }
        }
        t.actionREA.disabled = false;
        var m = "";
        m = "<table cellspacing=0 cellpadding=0 width=80%>";
        var cityID = 'city' + t.sourceCity.id;
        for (r = 1; r < 16; r++) {
            if (rownum++ % 2) style = '';
            else style = 'background: #e8e8e8;';
            m += '<tr style="' + style + '"><td align=right><img title="' + unsafeWindow.unitcost['unt' + r][0] + '" height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_' + r + '_30_s34.jpg></td>\
           <td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="REAdestunit' + r + '" type=text size=7 readonly value="' + parseIntNan(Seed.units[cityID]['unt' + r]) + '">&nbsp;\
           <input type=button value="->" id="REApdestunit' + r + '"  style="border:1px solid black;height:16px;font-size:11px;"></td></tr>';
        }
        m += "</table>";
        ById("REAstatsource").innerHTML = m;
        var knt = new Array();
        ById('REApiKnight').innerHTML = "";
        var o = document.createElement("option");
        o.text = uW.g_js_strings.modal_attack.dchooseknightd;
        o.value = 0;
        ById("REApiKnight").options.add(o);
        for (k in Seed.knights['city' + t.sourceCity.id]) {
            if (Seed.knights['city' + t.sourceCity.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.sourceCity.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["politicsKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["combatKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["intelligenceKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"]) {
                knt.push({
                    Name: Seed.knights['city' + t.sourceCity.id][k]["knightName"],
                    Combat: Seed.knights['city' + t.sourceCity.id][k]["combat"],
                    ID: Seed.knights['city' + t.sourceCity.id][k]["knightId"],
                });
            }
        }
        knt = knt.sort(function sort(a, b) {
            a = parseInt(a['Combat']);
            b = parseInt(b['Combat']);
            return a == b ? 0 : (a > b ? -1 : 1);
        });
        for (k in knt) {
            if (knt[k]["Name"] != undefined) {
                var o = document.createElement("option");
                o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] + ')')
                o.value = knt[k]["ID"];
                ById("REApiKnight").options.add(o);
            }
        }
        for (r = 1; r < 16; r++) {
            ById("REApdestunit" + r).addEventListener('click', function () {
                var nomcha = this.id.replace("REApdest", "REAdest");
                var nomcha2 = this.id.replace("REApdestunit", "REAnbunit");
                ById(nomcha2).value = 0;
                var e = 1;
                var f = uW.unixtime();
                if (Seed.playerEffects.aurasExpire) {
                    if (Seed.playerEffects.aurasExpire > f) {
                        e = 1.15
                    }
                }
                if (Seed.playerEffects.auras2Expire) {
                    if (Seed.playerEffects.auras2Expire > f) {
                        e = 1.3
                    }
                }
                if (uW.cm.PrestigeModel.isPrestige(t.sourceCity.id)) {
                    var b = uW.cm.PrestigeModel.getPrestigeLevel(t.sourceCity.id);
                    if (b > 0) {
                        var r = uW.cm.WorldSettings.getSetting("ASCENSION_RALLYPOINT_BOOST"),
                            m = uW.JSON.parse(r),
                            u = m.values[b - 1][1],
                            k = parseFloat(u);
                        e *= k;
                    }
                }
                var q = uW.cm.ThroneController.effectBonus(66);
                if (q > 150) q = 150;
                var niveauPointRall = parseInt(getCityBuilding(t.sourceCity.id, 12).maxLevel);
                var maxtroupe = parseInt(niveauPointRall * 10000 * e);
                if (niveauPointRall == 11) maxtroupe = parseInt(150000 * e);
                if (niveauPointRall == 12) maxtroupe = parseInt(200000 * e);
                maxtroupe = Math.round(maxtroupe * (1 + q / 100));
                var nbunitto = 0;
                for (r = 1; r < 16; r++) {
                    nbunitto += parseInt(ById("REAnbunit" + r).value);
                }
                var libre = parseInt(maxtroupe - nbunitto);
                if (ById(nomcha).value >= libre) {
                    ById(nomcha2).value = libre;
                } else {
                    ById(nomcha2).value = ById(nomcha).value;
                }
            }, false);
        }
        t.estimerTemps();
    },
    clickREACityDestinationSelect: function (city) {
        var t = Tabs.Reassign;
        var rownum = 0;
        t.destinationCity = city;
        var m = "";
        m = "<table cellspacing=0 cellpadding=0 width=80%>";
        for (r = 1; r < 16; r++) {
            if (rownum++ % 2) style = '';
            else style = 'background: #e8e8e8;';
            cityID = 'city' + t.destinationCity.id;
            m += '<tr style="' + style + '"><td align=right><img height=20 title="' + unsafeWindow.unitcost['unt' + r][0] + '" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_' + r + '_30_s34.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" type=text size=7 readonly value="' + parseIntNan(Seed.units[cityID]['unt' + r]) + '"></td></tr>';
        }
        m += "</table>";
        ById("REAstatdest").innerHTML = m;
        t.estimerTemps();
    },
}
//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/AutoTrain.js">
/************************************************************************************
 *                        KOC POWER - TABS AUTO TRAIN                                    *
 ************************************************************************************/
Tabs.AutoTrain= {
    tabOrder: TabOptions.toAutoTrain,
    tabLabel: culang.tabLabelAutoTrain,
    cont : null,
    nbfil : 0,
    crfil : 0,
    timer:null,
    city : 0,
    numcity :-1,
    init : function (div){
        var t = Tabs.AutoTrain;
        t.cont = div;
        t.state = null;

        AutoTrainObj = ById('pbAutoTrainState');
        if (TrainOptions.Running == false) {
            if (AutoTrainObj) AutoTrainObj.value = culang.buttonAutoTrain+" = "+culang.buttonOFF;
        } else {
            if (AutoTrainObj) AutoTrainObj.value = culang.buttonAutoTrain+" = "+culang.buttonON;
            t.timer=setTimeout(t.Start,5000);
        }

        if (TrainOptions.timelauch<5) {
            TrainOptions.timelauch=5;
            saveTrainingOptions();

        }
        return t.cont;
    },
    Start: function() {
        var t = Tabs.AutoTrain;
        if (!TrainOptions.Running) {
            clearTimeout(t.timer);
            return;
        }
        if (TrainOptions.throneCheck && Seed.throne.activeSlot != TrainOptions.throneSet) {
            actionLog(""+culang.tabLabelAutoTrain+"", culang.mainWrongThroneSet); //15.10.2012 Bommel
            clearTimeout(t.timer);
            t.timer=setTimeout(t.Start,parseIntNan(TrainOptions.timelauch*60)*1000);
            return;
        }
        
        if (t.numcity<Cities.numCities-1) {
            t.numcity++;
        } else {
            t.numcity=-1;
            clearTimeout(t.timer);

            t.timer=setTimeout(t.Start,parseIntNan(TrainOptions.timelauch*60)*1000);
            return;
        }
        
        
        var c=t.numcity;
        var cityId=Cities.cities[c].id;
        if (!TrainOptions.listactif[cityId]) t.Start();
        var populationdispo = 0;
        if(!TrainOptions.listlabour[cityId]) {
            populationdispo = parseIntNan(Seed.citystats['city'+cityId].pop[0]) - parseIntNan(Seed.citystats['city'+cityId].pop[3]);
        }else {
            populationdispo = parseIntNan(Seed.citystats['city'+cityId].pop[0]).toFixed(0);
        }
        var availableTrainingSlots = 0;
        var barracksTotal = getCityBuilding(cityId, 13).count;
        var trainingSlotsUsed = 0;
        var q = Seed.queue_unt['city'+cityId];
        for (var i=0; i< q.length; i++) {
            var qe = q[i];
            if (!qe[7]) {
                trainingSlotsUsed++;
            }
        }
        availableTrainingSlots = barracksTotal-trainingSlotsUsed;
        maxunite = t.unitemax(cityId, TrainOptions.list[Cities.cities[c].id],(c+1));
        var resources = t.checkresources(cityId, c);
        if (!resources) {
            actionLog(""+culang.tabLabelAutoTrain+"",Cities.cities[c].name+ " - "+culang.mainError+": "+culang.autoTrainActionLogResError+" <span class='boldGreen'>"+maxunite+"</span> "+culang.autoTrainActionLogResError2+" <span class='boldRed'>"+parseInt(TrainOptions.unitemin[Cities.cities[c].id])+"</span> "+culang.autoTrainActionLogResError3+" ");
            return;
        }
        if(availableTrainingSlots>0 && maxunite>=parseIntNan(TrainOptions.unitemin[Cities.cities[c].id]) && TrainOptions.listactif[Cities.cities[c].id]) {
            var unitId = TrainOptions.list[cityId];
            var num = parseInt(maxunite);
            if (TrainOptions.unitemax[Cities.cities[c].id] != undefined) {
                var maxnum = TrainOptions.unitemax[Cities.cities[c].id];
                if (num>parseInt(TrainOptions.unitemax[Cities.cities[c].id])) num=parseInt(TrainOptions.unitemax[Cities.cities[c].id]);
            }
            var gam= TrainOptions.listboost[cityId];
            var time = unsafeWindow.modal_barracks_traintime(unitId, num);
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.cid = cityId;
            params.type = unitId;
            params.quant = num;
            if (parseInt(TrainOptions.Item[(c+1)])) {
                params.items = TrainOptions.Item[(c+1)];
            }
            params.gambleId = gam;
            new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/train.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                loading: true,
                onSuccess: function(transport) {
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                        var resourceFactors=[],resourceLost;
                        if(gam!=null){
                            time=rslt.timeNeeded;
                        }
                        for(var i=1;i<5;i++){
                            if(rslt.gamble){
                                resourceFactors.push(rslt.gamble[i.toString()]);
                            }else{
                                resourceFactors.push(1);
                            }
                            resourceLost=parseInt(unsafeWindow.unitcost["unt"+unitId][i])*3600*parseInt(num);resourceLost=resourceLost*resourceFactors[i-1];
                            unsafeWindow.seed.resources["city"+cityId]["rec"+i][0]=parseInt(unsafeWindow.seed.resources["city"+cityId]["rec"+i][0])-resourceLost;
                        }
                        unsafeWindow.seed.citystats["city"+cityId].gold[0]=parseInt(unsafeWindow.seed.citystats["city"+cityId].gold[0])-parseInt(unsafeWindow.unitcost["unt"+unitId][5])*parseInt(num);
                        unsafeWindow.seed.citystats["city"+cityId].pop[0]=parseInt(unsafeWindow.seed.citystats["city"+cityId].pop[0])-parseInt(unsafeWindow.unitcost["unt"+unitId][6])*parseInt(num);
                        unsafeWindow.seed.queue_unt["city"+cityId].push([unitId,num,rslt.initTS,parseInt(rslt.initTS)+time,0,time,null]);

                        if(rslt.updateSeed) { unsafeWindow.update_seed(rslt.updateSeed) }
                        actionLog(""+culang.tabLabelAutoTrain+"",Cities.cities[c].name+" - " + num+" "+unsafeWindow.unitcost['unt'+ TrainOptions.list[Cities.cities[c].id]][0]+" "+culang.mainOK+"");
                    } else {
                        actionLog(""+culang.tabLabelAutoTrain+"",Cities.cities[c].name+ " - " + num+" "+unsafeWindow.unitcost['unt'+ TrainOptions.list[Cities.cities[c].id]][0]+"<br><font color=red>" + transport.responseText +"</font>");
                    }
                },
                onFailure: function(o) {
                    actionLog(""+culang.tabLabelAutoTrain+"",Cities.cities[c].name+ " - " + num+" "+unsafeWindow.unitcost['unt'+ TrainOptions.list[Cities.cities[c].id]][0]+"<br><font color=red>" +o.responseText+"</font>");
                }
            });
        } else {
            if (availableTrainingSlots<=0) {
                actionLog(""+culang.tabLabelAutoTrain+"",Cities.cities[c].name+ " - "+culang.mainError+": "+culang.autoTrainActionLogSlotError+"");
            }
            if (maxunite<parseInt(TrainOptions.unitemin[Cities.cities[c].id])) {
                actionLog(""+culang.tabLabelAutoTrain+"",Cities.cities[c].name+ " - "+culang.mainError+": "+culang.autoTrainActionLogPopResError+" "+maxunite+" "+culang.autoTrainActionLogPopResError2+" "+parseInt(TrainOptions.unitemin[Cities.cities[c].id])+" "+culang.autoTrainActionLogPopResError3+"");
            }
        }

        var cityNo = t.numcity + 1;
        if (TrainOptions.doTraps[cityNo])
            t.doAutoTraps(cityNo);
        if (TrainOptions.doCalrops[cityNo])
            t.doAutoCaltrops(cityNo);
        if (TrainOptions.doSpikes[cityNo])
            t.doAutoSpikes(cityNo);
        if (TrainOptions.doXbows[cityNo])
            t.doAutoCrossbows(cityNo);
        if (TrainOptions.doTrebu[cityNo])
            t.doAutoTrebu(cityNo);


        clearTimeout(t.timer);
        t.timer=setTimeout(function() { t.Start(); },5000);

    },

    doAutoTraps: function (cityNo) {
        var t = Tabs.AutoTrain;
        wall = {};
        var cityId = Cities.cities[cityNo - 1].id
        var cityID = 'city'+ cityId;
        getWallInfo (cityId, wall);
        availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
        if (availableSpace > 0 && wall.slotsBusy < 3) {
            var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
            var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
            var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
            var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
            availableSlots = 3 - wall.slotsBusy;
            var foodRes = TrainOptions.keepFood[cityNo];
            var woodRes = TrainOptions.keepWood[cityNo];
            var stoneRes = TrainOptions.keepStone[cityNo];
            var oreRes = TrainOptions.keepOre[cityNo];
            var availFood = food - foodRes;
            var availWood = wood - woodRes;
            var availStone = stone - stoneRes;
            var availOre = ore - oreRes;
            secsPerTrap = Cities.byID[cityId]['Def60Time'];
            if (secsPerTrap > 0 && availableSpace > 4 && availableSlots > 0) {
                if (availFood > 400 && availWood > 800 & availStone > 200 & availOre > 400) {
                    var numberToTrain = 9999999999;
                    if ((availFood / 400) < numberToTrain)
                        numberToTrain = parseInt(availFood / 400);
                    if ((availWood / 800) < numberToTrain)
                        numberToTrain = parseInt(availWood / 800);
                    if ((availStone / 200) < numberToTrain)
                        numberToTrain = parseInt(availStone / 200);
                    if ((availOre / 400) < numberToTrain)
                        numberToTrain = parseInt(availOre / 400);
                    if (numberToTrain > 5)
                        numberToTrain = 5;
                    if (wall.Trap + wall.TrapTraining < 10 || availableSpace < 15) {
                        numberToTrain = 1;
                    }
                    actionLog(""+culang.tabLabelAutoTrain+"",Cities.byID[cityId].name + ' - '+culang.autoTrainWallLog+' ' + numberToTrain + ' '+culang.autoTrainWallLogTraps+' ');
                    doDefTrain (cityId, 0, 60, numberToTrain);
                }
            }
        }
    },
    doAutoCaltrops: function (cityNo) {
        var t = Tabs.AutoTrain;
        var wall = {};
        var cityId = Cities.cities[cityNo - 1].id;
        var cityID = 'city'+ cityId;
        getWallInfo (cityId, wall);
        availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
        if (availableSpace > 0 && wall.slotsBusy < 3) {
            var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
            var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
            var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
            var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
            availableSlots = 3 - wall.slotsBusy;
            var foodRes = TrainOptions.keepFood[cityNo];
            var woodRes = TrainOptions.keepWood[cityNo];
            var stoneRes = TrainOptions.keepStone[cityNo];
            var oreRes = TrainOptions.keepOre[cityNo];
            var availFood = food - foodRes;
            var availWood = wood - woodRes;
            var availStone = stone - stoneRes;
            var availOre = ore - oreRes;
            secsPerCaltrop = Cities.byID[cityId]['Def61Time'];
            if (secsPerCaltrop > 0 && availableSpace > 1 && availableSlots > 0) {
                if (availFood > 100 && availOre > 400) {
                    var numberToTrain = 9999999999;
                    if ((availFood / 100) < numberToTrain)
                        numberToTrain = parseInt(availFood / 100);
                    if ((availOre / 400) < numberToTrain)
                        numberToTrain = parseInt(availOre / 400);
                    if (numberToTrain > 5)
                        numberToTrain = 5;
                    if (wall.Caltrops + wall.CaltropsTraining < 10 || availableSpace < 15) {
                        numberToTrain = 1;
                    }
                    actionLog(""+culang.tabLabelAutoTrain+"",Cities.byID[cityId].name + ' - '+culang.autoTrainWallLog+' ' + numberToTrain + ' '+culang.autoTrainWallLogCaltrops+' ');
                    doDefTrain (cityId,0,61,numberToTrain);
                }
            }
        }
    },
    doAutoSpikes: function (cityNo) {
        var t = Tabs.AutoTrain;
        wall = {};
        var cityId = Cities.cities[cityNo - 1].id
        var cityID = 'city'+ cityId;
        getWallInfo (cityId, wall);
        availableSpace = wall.fieldSpace - wall.fieldSpaceUsed;
        if (availableSpace > 0 && wall.slotsBusy < 3) {
            var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
            var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
            var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
            var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
            availableSlots = 3 - wall.slotsBusy;
            var foodRes = TrainOptions.keepFood[cityNo];
            var woodRes = TrainOptions.keepWood[cityNo];
            var stoneRes = TrainOptions.keepStone[cityNo];
            var oreRes = TrainOptions.keepOre[cityNo];
            var availFood = food - foodRes;
            var availWood = wood - woodRes;
            var availStone = stone - stoneRes;
            var availOre = ore - oreRes;
            secsPerSpike = Cities.byID[cityId]['Def62Time'];
            if (secsPerSpike > 0 && availableSpace > 3 && availableSlots > 0) {
                if (availFood > 150 && availWood > 750 & availStone > 50) {
                    var numberToTrain = 9999999999;
                    if ((availFood / 150) < numberToTrain)
                        numberToTrain = parseInt(availFood / 150);
                    if ((availWood / 750) < numberToTrain)
                        numberToTrain = parseInt(availWood / 750);
                    if ((availStone / 50) < numberToTrain)
                        numberToTrain = parseInt(availStone / 50);
                    if (numberToTrain > 5)
                        numberToTrain = 5;
                    if (wall.SpikedBarrier + wall.SpikedBarrierTraining < 10 || availableSpace < 15) {
                        numberToTrain = 1;
                    }
                    actionLog(""+culang.tabLabelAutoTrain+"",Cities.byID[cityId].name + ' - '+culang.autoTrainWallLog+' ' + numberToTrain + ' '+culang.autoTrainWallLogSpikes+' ');
                    doDefTrain (cityId, 0, 62, numberToTrain);
                }
            }
        }
    },
    doAutoCrossbows: function (cityNo) {
        var t = Tabs.AutoTrain;
        wall = {};
        var cityId = Cities.cities[cityNo - 1].id
        var cityID = 'city'+ cityId;
        getWallInfo (cityId, wall);
        availableSpace = wall.wallSpace - wall.wallSpaceUsed;
        if (availableSpace > 0 && wall.slotsBusy < 2) {
            var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
            var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
            var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
            var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
            availableSlots = 2 - wall.slotsBusy;
            var foodRes = TrainOptions.keepFood[cityNo];
            var woodRes = TrainOptions.keepWood[cityNo];
            var stoneRes = TrainOptions.keepStone[cityNo];
            var oreRes = TrainOptions.keepOre[cityNo];
            var availFood = food - foodRes;
            var availWood = wood - woodRes;
            var availStone = stone - stoneRes;
            var availOre = ore - oreRes;
            secsPerXbow = Cities.byID[cityId]['Def53Time'];
            if (secsPerXbow > 0 && availableSpace > 2 && availableSlots > 0) {
                if (availFood > 250 && availWood > 2000 & availStone > 750 & availOre > 500) {
                    var numberToTrain = 9999999999;
                    if ((availFood / 250) < numberToTrain)
                        numberToTrain = parseInt(availFood / 250);
                    if ((availWood / 2000) < numberToTrain)
                        numberToTrain = parseInt(availWood / 2000);
                    if ((availStone / 750) < numberToTrain)
                        numberToTrain = parseInt(availStone / 750);
                    if ((availOre / 500) < numberToTrain)
                        numberToTrain = parseInt(availOre / 500);
                    if (numberToTrain > 5)
                        numberToTrain = 5;
                    if (wall.Crossbows + wall.CrossbowsTraining < 10 || availableSpace < 15) {
                        numberToTrain = 1;
                    }
                    actionLog(""+culang.tabLabelAutoTrain+"",Cities.byID[cityId].name + ' - '+culang.autoTrainWallLog+' ' + numberToTrain + ' '+culang.autoTrainWallLogCrossbows+' ');
                    doDefTrain (cityId, 0, 53, numberToTrain);
                }
            }
        }
    },
    doAutoTrebu: function (cityNo) {
        var t = Tabs.AutoTrain;
        wall = {};
        var cityId = Cities.cities[cityNo - 1].id
        var cityID = 'city'+ cityId;
        getWallInfo (cityId, wall);
        availableSpace = wall.wallSpace - wall.wallSpaceUsed;
        if (availableSpace > 0 && wall.slotsBusy < 2) {
            var food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
            var wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
            var stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
            var ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
            availableSlots = 2 - wall.slotsBusy;
            var foodRes = TrainOptions.keepFood[cityNo];
            var woodRes = TrainOptions.keepWood[cityNo];
            var stoneRes = TrainOptions.keepStone[cityNo];
            var oreRes = TrainOptions.keepOre[cityNo];
            var availFood = food - foodRes;
            var availWood = wood - woodRes;
            var availStone = stone - stoneRes;
            var availOre = ore - oreRes;
            secsPerTrebu = Cities.byID[cityId]['Def55Time'];
            if (secsPerTrebu > 0 && availableSpace > 4 && availableSlots > 0) {
                if (availFood > 500 && availWood > 3500 & availStone > 1800 & availOre > 1200) {
                    var numberToTrain = 9999999999;
                    if ((availFood / 500) < numberToTrain)
                        numberToTrain = parseInt(availFood / 500);
                    if ((availWood / 3500) < numberToTrain)
                        numberToTrain = parseInt(availWood / 3500);
                    if ((availStone / 1800) < numberToTrain)
                        numberToTrain = parseInt(availStone / 1800);
                    if ((availOre / 1200) < numberToTrain)
                        numberToTrain = parseInt(availOre / 1200);
                    if (numberToTrain > 5)
                        numberToTrain = 5;
                    if (wall.Trebuchet + wall.TrebuchetTraining < 10 || availableSpace < 15) {
                        numberToTrain = 1;
                    }
                    actionLog(""+culang.tabLabelAutoTrain+"",Cities.byID[cityId].name + ' - '+culang.autoTrainWallLog+' ' + numberToTrain + ' '+culang.autoTrainWallLogTrebuchet+' ');
                    doDefTrain (cityId, 0, 55, numberToTrain);
                }
            }
        }
    },
    unitemax : function(currentcityid, e, numcity){

        var gumble = TrainOptions.listboost[currentcityid];
        var mult=1;
        if (gumble==0) mult=1;
        if (gumble==1) mult=2;
        if (gumble==2) mult=4;
        var b=new Array();
        var a=new Array();
        for(var d=1;d<5;d++){
            b.push((parseInt(unsafeWindow.unitcost["unt"+e][d])*3600)*mult);
            a.push(parseInt(unsafeWindow.seed.resources["city"+currentcityid]["rec"+d][0]))
        }
        b.push((parseInt(unsafeWindow.unitcost["unt"+e][5]))*mult);
        a.push(parseInt(unsafeWindow.seed.citystats["city"+currentcityid].gold[0]));
        b.push((parseInt(unsafeWindow.unitcost["unt"+e][6])));

        if (!TrainOptions.listlabour[currentcityid]) {
            a.push(parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[0])-parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[3]));
        } else {
            a.push(parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[0])-parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[3])+ parseInt((parseInt(unsafeWindow.seed.citystats["city"+currentcityid].pop[3])*(TrainOptions.Workers[numcity]/100))));
        }
        var c=a[0]/b[0];
        for(var d=1;d<b.length;d++)
        {
            if(parseInt(b[d])!=0){
                c=Math.min(c,a[d]/b[d])
            }
        }
        if (c<0) c=0
        return parseInt(c)||0
    },
    hide : function (){
        var t = Tabs.AutoTrain;
        t.saveOptionsAutoF();
    },

    show : function (){
        var t = Tabs.AutoTrain;
        if (TrainOptions.throneSet == undefined) TrainOptions.throneSet = 1;
        unsafeWindow.Ks_AF_TU_Change = t.AF_TU_Change;
        m = "<DIV class=pdxStat>"+culang.autoTrainHead+" - <input type=button value='?' id=boaideautoform class=buttonHelp></div>";
        m += '<div style=""><TABLE width=95% class=pdxTab border=0 align=center>\
        <tr align=center valign=top><TD><B>'+culang.mainIntervall+'</b>: <input id=aFtimelauch type=text size=2 value="'+parseInt(TrainOptions.timelauch)+'"> '+culang.mainMinutes+'</TD>';

        m += '<TD><INPUT id=autoMilicienstoggle type=submit value="'+culang.autoTrainMode+'"><select id=KsModeFA>';
        for (r=1; r<=12; r++){
            m+= "<option value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
        }
        m+="</select></td>";
        //ThroneSet 
        m+="<td><input type=checkbox id=Ks_AF_throneCheck "+ (TrainOptions.throneCheck?'CHECKED':'') +"> " + culang.mainTrainOnlyThroneSet + " <SELECT id=Ks_AF_throneSet>"; //15.10.2012 Bommel
        for (i=1;i<=Seed.throne.slotNum;i++){
            m += '<option value="'+i+'">'+i+'</option>';
        }
        m +='</select></td>';

        if (TrainOptions.Running == false) {
            m += '<TD><INPUT id=pbAutoTrainState type=submit value="'+culang.buttonAutoTrain+' = '+culang.buttonOFF+'"></td>';
        } else {
            m += '<TD><INPUT id=pbAutoTrainState type=submit value="'+culang.buttonAutoTrain+' = '+culang.buttonON+'"></td>';
            // t.timer=setTimeout(t.Start,5000);
            saveTrainingOptions();
        }
        m+="</tr></table><div id='Ks_AF_Progression' style='max-height:100px; overflow:auto'></div>";

        m += '<DIV class=pdxStat2><a href="#" onclick="document.getElementById(\'autoTrainOpt\').style.display=(document.getElementById(\'autoTrainOpt\').style.display== \'block\')?\'none\':\'block\';">'+culang.autoTrainHeadOptions+'</a></div>';
        m += '<DIV id="autoTrainOpt" style="display:none;">';
        m += '<table width=98% class=pdxTab border=0 align=left>\
    <tr><td>'+culang.autoTrainCalcWorkers+' <select id=KsModeDiv><option value=25>25%</option><option value=50>50%</option><option value=75>75%</option><option value=90>90%</option><option value=100>100%</option></select> - <input type=button value="'+culang.autoTrainCalculate+'" id=Ks_AllCalculate></td></tr>';
        m += "<tr><td><input type=checkbox id=Ks_AF_CancelFirst> "+culang.autoTrainDelete+" </td><td><input type=button value='"+culang.autoTrainDeleteAll+"' id=Ks_AF_CancelAll></td></tr>\
    <tr><td><sup><span class='boldRed'><u>"+culang.mainImportant+"</u></span>:</sup> <span class='helpText'>"+culang.autoTrainWallBuildNote+"</span></td></tr></table>";
        m += '</div>';
        m += "<TABLE width=98% class=pdxTab border=0 align=center cellspacing=0 cellpadding=1 align=left>\
          <tr align=center><td align=center style='border-bottom:1px solid #141516;' colspan=2><b><u>"+culang.mainCastle+"</u></td>\
          <td align=center style='border-bottom:1px solid #141516;'><b><u>"+culang.autoTrainUnitType+"</u></td>\
          <td align=center style='border-bottom:1px solid #141516;'><b><u>"+culang.shortMin+"</u></td>\
          <td align=center style='border-bottom:1px solid #141516;'><b><u>"+culang.shortMax+"</u></td>\
          <td align=center style='border-bottom:1px solid #141516;' colspan=2><a id='Ks_WorkersCalc'><b>"+culang.autoTrainWorker+"</a></td>\
          <tD align=center style='border-bottom:1px solid #141516;'><b><u>"+culang.mainSpeedups+"</u></td></tr>";
        var city=0;
        for (var c=0; c<Cities.numCities; c++) {
            cityId=Cities.cities[c].id;
            city = c+1;
            m+="<tr><td rowspan=3 width=10% align=left style='border-bottom:1px solid #141516;'><b>"+(c+1)+"</b> : "+Cities.cities[c].name+"<br></td><td align=right rowspan=3 style='border-bottom:1px solid #141516;'>";
            if (TrainOptions.listactif && TrainOptions.listactif[cityId] == false) {
                m+="<input type=checkbox id='autoFCheck_"+cityId+"'>";
            }else {
                m+="<input checked type=checkbox id='autoFCheck_"+cityId+"'>";
            }
            m+="</td><TD align=center><SELECT id='autoFType_"+cityId+"' onchange='Ks_AF_TU_Change("+cityId+",this.value);'>";
            for (r=1; r<16; r++){
                var faux = 0;
                var uc = unsafeWindow.unitcost['unt'+r];
                if (matTypeof(uc[8]) == 'object'){
                    for (k in uc[8]){
                        var b = getCityBuilding (cityId, k.substr(1));
                        if (b.maxLevel < uc[8][k][1]){
                            faux = 1;
                            break;
                        }
                    }
                }
                
                if (matTypeof(uc[9]) == 'object'){
                    for (k in uc[9]){
                        if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
                            faux = 1;
                            break;
                        }
                    }
                }
                
                if (r == 13) {
                    if (Seed.cityData.city[cityId].isPrestigeCity && Seed.cityData.city[cityId].prestigeInfo.prestigeType == 1) {
                        //Amazonen sind erlaubt in Druidenstadt
                    } else {
                        //Amazonen sind nicht erlaubt
                        faux = 1;
                    }
                }
                if (r == 14) {
                    if (Seed.cityData.city[cityId].isPrestigeCity && Seed.cityData.city[cityId].prestigeInfo.prestigeType == 2) {
                        //Executioner sind erlaubt in Feystadt
                    } else {
                        //Executioner sind nicht erlaubt
                        faux = 1;
                    }
                }
                if (r == 15) {
                    if (Seed.cityData.city[cityId].isPrestigeCity && Seed.cityData.city[cityId].prestigeInfo.prestigeType == 3) {
                        //Siege Wall sind erlaubt in Britenstadt
                    } else {
                        //Siege Wall sind nicht erlaubt
                        faux = 1;
                    }
                }
                if (faux==0) {
                    if (TrainOptions.list) {
                        if (r==TrainOptions.list[cityId]) {
                            m+= "<option selected value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
                        } else {
                            m+= "<option value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
                        }
                    }else{
                        if (r==2) {
                            m+= "<option selected value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
                        } else {
                            m+= "<option value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
                        }
                    }
                }
            }
            if (TrainOptions.unitemax[Cities.cities[c].id] == undefined) TrainOptions.unitemax[Cities.cities[c].id] = 999999;
            if (isNaN(parseInt(TrainOptions.unitemin[cityId]))) TrainOptions.unitemin[cityId]=0 ;
            if (TrainOptions.Keep[city] == undefined) TrainOptions.Keep[city] ={};
            m+= "</select></td><td align=left><input type=text value='"+ parseIntNan(TrainOptions.unitemin[cityId]) +"' id='aFunitemin_"+cityId+"' size=4></td><td align=left><input type=text value='"+ parseIntNan(TrainOptions.unitemax[cityId]) +"' id='aFunitemax_"+cityId+"' size=5></td><td align=right>";
            if (TrainOptions.listlabour && TrainOptions.listlabour[cityId] == false) {
                m+="<input type=checkbox class="+city+" id='autoFWorkers_"+cityId+"'>";
            }else {
                m+="<input checked class="+city+" type=checkbox id='autoFWorkers_"+cityId+"'>";
            }
            m+="</td><td align=right>";
            m+='<SELECT class='+city+' id="workers'+city+'"><option value="0">0%</options>';
            m+='<option value="25">25%</options><option value="50">50%</options><option value="75">75%</options><option value="100">100%</options></select></td><td align=right>';
            m+="<select id='autoFboost_"+cityId+"'>";
            m+="<option value=0>"+culang.mainNormal+"</option><option value=1 "+ (TrainOptions.listboost[cityId]==1?'SELECTED ':'') +">5-15%</option><option value=2 "+ (TrainOptions.listboost[cityId]==2?'SELECTED ':'') +">10-25%</option></select>";
            m+='<br><select class='+city+' id="TrainSpeedItem_'+city+'"><option value=0><CENTER>-- '+unsafeWindow.g_js_strings.commonstr.items+' --</center></option>\
             <option value=36>'+unsafeWindow.itemlist.i36.name+'</option>\
              <option value=37>'+unsafeWindow.itemlist.i37.name+'</option>\
            <option value=38>'+unsafeWindow.itemlist.i38.name+'</option></select></td></tr>';
            m+='<TR><td colspan=6><img width=23 src="'+IMGfood30+'">&nbsp;';
            m += '<INPUT class='+city+'  id="KeepFood'+city+'" type=text size=7 maxlength=8 value="'+ parseIntNan(TrainOptions.Keep[city]['Food'])+'"\>&nbsp;';
            m += '<img width=23 src="'+IMGwood30+'">&nbsp;';
            m += '<INPUT class='+city+' id="KeepWood'+city+'" type=text size=7 maxlength=8 value="'+ parseIntNan(TrainOptions.Keep[city]['Wood'])+'"\>&nbsp;';
            m += '<img width=23 src="'+IMGstone30+'">&nbsp;';
            m += '<INPUT class='+city+'  id="KeepStone'+city+'" type=text size=7 maxlength=8 value="'+ parseIntNan(TrainOptions.Keep[city]['Stone'])+'"\>&nbsp;';
            m += '<img width=23 src="'+IMGiron30+'">&nbsp;';
            m += '<INPUT class='+city+' id="KeepOre'+city+'" type=text size=7 maxlength=8 value="'+ parseIntNan(TrainOptions.Keep[city]['Ore'])+'"\>';
            m += "</td></tr><TR><td colspan=8 style='border-bottom:1px solid #141516;'><b>"+culang.autoTrainWallBuild+"</b> <INPUT class="+city+" type=CHECKBOX id='chkDoTraps"+city+"' "+ (TrainOptions.doTraps[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt60[0]+"&nbsp;\
            <INPUT class="+city+" type=CHECKBOX id='chkDoCaltrops"+city+"' "+ (TrainOptions.doCalrops[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt61[0]+"&nbsp;\
            <INPUT class="+city+" type=CHECKBOX id='chkDoSpikes"+city+"' "+ (TrainOptions.doSpikes[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt62[0]+"&nbsp;\
            <INPUT class="+city+" type=CHECKBOX id='chkDoXbows"+city+"' "+ (TrainOptions.doXbows[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt53[0].substr(0,9)+"&nbsp;\
           <INPUT class="+city+" type=CHECKBOX id='chkDoTrebu"+city+"' "+ (TrainOptions.doTrebu[city]?' CHECKED ':'') +">"+unsafeWindow.fortcost.frt55[0]+"</TD></TR>";

        }
        m+="</table></div><div>";

        t.cont.innerHTML = m;

        ById('Ks_AF_throneCheck').addEventListener ('click', function(e){
            TrainOptions.throneCheck = e.target.checked;
            saveTrainingOptions();
        }, false);
        ById('Ks_AF_throneSet').value = TrainOptions.throneSet;
        ById('Ks_AF_throneSet').addEventListener ('change',function(e){
            TrainOptions.throneSet = this.value;
            saveTrainingOptions();
        }, false);
        
        ById('boaideautoform').addEventListener('click', function(){
            window.open(homePage+" ");
        } , false);
        for (i=0;i<Seed.cities.length;i++){
            city = i+1;
            cityId=Cities.cities[i].id;
            ById('workers'+city).value = TrainOptions.Workers[city];
            ById('TrainSpeedItem_'+city).value = TrainOptions.Item[city];
            //??ById('autoFboost_'+cityId).value = TrainOptions.Item[city];
        }
        ById('KsModeDiv').value=TrainOptions.UnitMixValue;
        ById('KsModeDiv').addEventListener('change', function(e){
            TrainOptions.UnitMixValue=ById('KsModeDiv').value;
            for (var c=0; c<Cities.numCities; c++) {
                cityId=Cities.cities[c].id;
                t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);
            }

        },false);
        ById('Ks_WorkersCalc').addEventListener('click', function(){
            t.workers();
        } , false);
        ById('Ks_AllCalculate').addEventListener('click', function(){
            for (var c=0; c<Cities.numCities; c++) {
                cityId=Cities.cities[c].id;
                t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);
            }

        } , false);
        ById('pbAutoTrainState').addEventListener('click', function(){t.toggleAutoTrainState(this)} , false);
        ById('autoMilicienstoggle').addEventListener('click', function(){t.milicien()} , false);
        ById('Ks_AF_CancelAll').addEventListener('click', function(){t.AF_CancelAll()} , false);
        t.dispStatus = ById('Ks_AF_Progression');
        var k=0;
        window.addEventListener('unload', t.onUnload, false);
        for (var c=0; c<Cities.numCities; c++) {
            k=c+1;
            cityID=Cities.cities[c].id;
            ById('autoFWorkers_'+cityID).addEventListener('click', function(e){

                cityId=Cities.cities[(e.target['className']-1)].id;
                TrainOptions.listlabour[cityId] = ById('autoFWorkers_'+cityId).checked;
                t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);

            },false);


            ById('workers'+k).addEventListener('change', function(e){
                TrainOptions.Workers[e.target['className']] = e.target.value;
                cityId=Cities.cities[(e.target['className']-1)].id;
                t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);

            }, false);
            ById('TrainSpeedItem_'+k).addEventListener('change', function(e){
                TrainOptions.Item[e.target['className']] = e.target.value;
                saveTrainingOptions();
            }, false);
            ById('chkDoTraps'+k).addEventListener('click', function(e){
                TrainOptions.doTraps[e.target['className']] = e.target.checked;
                saveTrainingOptions();
            }, false);
            ById('chkDoCaltrops'+k).addEventListener('click', function(e){
                TrainOptions.doCalrops[e.target['className']] = e.target.checked;
                saveTrainingOptions();
            }, false);
            ById('chkDoSpikes'+k).addEventListener('click', function(e){
                TrainOptions.doSpikes[e.target['className']] = e.target.checked;
                saveTrainingOptions();
            }, false);
            ById('chkDoXbows'+k).addEventListener('click', function(e){
                TrainOptions.doXbows[e.target['className']] = e.target.checked;
                saveTrainingOptions();
            }, false);
            ById('chkDoTrebu'+k).addEventListener('click', function(e){
                TrainOptions.doTrebu[e.target['className']] = e.target.checked;
                saveTrainingOptions();
            }, false);
            ById('KeepFood'+k).addEventListener('change', function(e){
                if (isNaN(e.target.value)) e.target.value=0 ;
                TrainOptions.Keep[e.target['className']]['Food'] = e.target.value;
                saveTrainingOptions();
            }, false);
            ById('KeepWood'+k).addEventListener('change', function(e){
                if (isNaN(e.target.value)) e.target.value=0 ;
                TrainOptions.Keep[e.target['className']]['Wood'] = e.target.value;
                saveTrainingOptions();
            }, false);
            ById('KeepStone'+k).addEventListener('change', function(e){
                if (isNaN(e.target.value)) e.target.value=0 ;
                TrainOptions.Keep[e.target['className']]['Stone'] = e.target.value;
                saveTrainingOptions();
            }, false);
            ById('KeepOre'+k).addEventListener('change', function(e){
                if (isNaN(e.target.value)) e.target.value=0 ;
                TrainOptions.Keep[e.target['className']]['Ore'] = e.target.value;
                saveTrainingOptions();
            }, false);
        }
    },
    unload:function() {
        var t = Tabs.AutoTrain;
        t.saveOptionsAutoF();
    },
    checkresources : function(cityId, city){
        var t = Tabs.AutoTrain;
        var city=city+1;
        t.food = parseInt((Seed.resources['city'+cityId].rec1[0]/3600) - parseIntNan(TrainOptions['Keep'][city]['Food']));
        t.wood = parseInt((Seed.resources['city'+cityId].rec2[0]/3600) - parseIntNan(TrainOptions['Keep'][city]['Wood']));
        t.stone = parseInt((Seed.resources['city'+cityId].rec3[0]/3600) - parseIntNan(TrainOptions['Keep'][city]['Stone']));
        t.ore = parseInt((Seed.resources['city'+cityId].rec4[0]/3600) - parseIntNan(TrainOptions['Keep'][city]['Ore']));
        if(t.food>0 && t.wood>0 && t.stone>0 && t.ore>0){
            return true;
        }
        return false;
    },
    AF_TU_Change: function(cityId,unit) {
        var t = Tabs.AutoTrain;
        var coutenpop= unsafeWindow.unitcost['unt'+unit][6];
        var numcity=Cities.byID[cityId].idx+1;
        var X = Seed.citystats['city'+cityId]["pop"][1];
        var Y = unsafeWindow.seed.citystats["city"+cityId].pop[3];
        var Q= coutenpop;
        var Z = 0;
        var M = ById("KsModeDiv").value/100;
        if (ById("autoFWorkers_"+cityId).checked) {
            Z = ById('workers'+numcity).value/100;
            ById("aFunitemax_"+cityId).value = parseIntNan(X/Q);
        } else {
            Z = 0;
            ById("aFunitemax_"+cityId).value=parseIntNan((X-Y)/Q);
        }
        var Min =((X-(Y*(1-Z)))*M)/Q;
        if (Min<0) Min=0;
        ById("aFunitemin_"+cityId).value = parseIntNan(Min);
        if (ById("aFunitemax_"+cityId).value<0) { ById("aFunitemax_"+cityId).value=0;ById("aFunitemin_"+cityId).value =0; }
        t.saveOptionsAutoF();
    },

    workers:function() {
        var t = Tabs.AutoTrain;
        for (var c=0; c<Cities.numCities; c++) {
            if (ById('workers'+(c+1)).value == "100")
                ById('workers'+(c+1)).value = "25"
            else
                ById('workers'+(c+1)).value = "100";

            TrainOptions.Workers[(c+1)] = ById('workers'+(c+1)).value ;
            cityId=Cities.cities[c].id;
            t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);
        }
        t.saveOptionsAutoF();
    },
    milicien: function() {
        var t = Tabs.AutoTrain;
        var typeunite = ById('KsModeFA').value;
        ById('KsModeDiv').value="90";
        var coutenpop= unsafeWindow.unitcost['unt'+typeunite][6];
        for (var c=0; c<Cities.numCities; c++) {
            cityId=Cities.cities[c].id;
            ById("autoFWorkers_"+Cities.cities[c].id).checked=true;
            ById("autoFCheck_"+Cities.cities[c].id).checked=true;
            ById("autoFType_"+Cities.cities[c].id).value=typeunite;
            t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);
        }
        for (var c=0; c<Cities.numCities; c++) {
            cityId=Cities.cities[c].id;
            t.AF_TU_Change(cityId,ById("autoFType_"+cityId).value);
        }
        t.saveOptionsAutoF();
    },
    saveOptionsAutoF: function() {
        var t = Tabs.AutoTrain;
        if (parseIntNan(ById('aFtimelauch').value) < 5)  ById('aFtimelauch').value = "5";
        TrainOptions.timelauch=ById('aFtimelauch').value;
        TrainOptions.UnitMixValue=ById('KsModeDiv').value;
        TrainOptions.list={};
        TrainOptions.listactif={};
        TrainOptions.listlabour={};
        TrainOptions.unitemin={};
        TrainOptions.unitemax={};
        TrainOptions.listboost={};
        for (var c=0; c<Cities.numCities; c++) {
            TrainOptions.list[Cities.cities[c].id] = ById('autoFType_'+Cities.cities[c].id).value;
            TrainOptions.listactif[Cities.cities[c].id] = ById('autoFCheck_'+Cities.cities[c].id).checked;
            TrainOptions.listlabour[Cities.cities[c].id] = ById('autoFWorkers_'+Cities.cities[c].id).checked;
            TrainOptions.unitemin[Cities.cities[c].id]=parseIntNan(ById('aFunitemin_'+Cities.cities[c].id).value);
            TrainOptions.unitemax[Cities.cities[c].id]=parseIntNan(ById('aFunitemax_'+Cities.cities[c].id).value);
            TrainOptions.listboost[Cities.cities[c].id]=ById('autoFboost_'+Cities.cities[c].id).value;
            TrainOptions.Workers[(c+1)] = ById('workers'+(c+1)).value;
            TrainOptions.Item[(c+1)] = ById('TrainSpeedItem_'+(c+1)).value;
        }
        saveTrainingOptions();
    },
    toggleAutoTrainState : function(obj) {
        var t = Tabs.AutoTrain;
        obj = ById('pbAutoTrainState');
        if (TrainOptions.Running == true) {
            TrainOptions.Running = false;
            clearTimeout(t.timer);
            if (obj) obj.value = culang.buttonAutoTrain+" = "+culang.buttonOFF;
            saveTrainingOptions();
        }  else {
            TrainOptions.Running = true;
            clearTimeout(t.timer);
            t.numcity=-1;
            t.timer=setTimeout(t.Start,5000);
            if (obj) obj.value = culang.buttonAutoTrain+" = "+culang.buttonON;
            saveTrainingOptions();
        }
    },

    CancelActionall: function(numville, num, fintraitement) {

        var t = Tabs.AutoTrain;
        var first=1;
        var cityId = Cities.cities[numville].id;
        var q = Seed.queue_unt['city'+cityId];
        var now = unixTime();
        start = q[num][2];
        end = q[num][3];
        actual = end - now;
        if (actual < 0) actual = 0;
        var param2=cityId;
        var param3=q[num][0];
        var param4=q[num][1];
        var param5=end;t
        var param6=start;
        var param7=actual;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cityId = param2;
        params.requestType ="CANCEL_TRAINING";
        params.numtrptrn = param4;
        params.trnETA= param5;
        params.trnNeeded = param7;
        params.trnTmp = param6;
        params.typetrn= param3;

        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelTraining.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                var t = Tabs.AutoTrain;
                if (rslt.ok) {
                    unsafeWindow.update_seed_ajax(true,function(){
                        var k=0;for(var j=0;j<unsafeWindow.seed.queue_unt["city"+param2].length;j++){
                            if(j>num){
                                unsafeWindow.seed.queue_unt["city"+param2][j][2]=parseInt(rslt.dateTraining[k]["start"]);
                                unsafeWindow.seed.queue_unt["city"+param2][j][3]=parseInt(rslt.dateTraining[k]["end"]);
                                k++;
                            }
                        }
                        unsafeWindow.seed.queue_unt["city"+param2].splice(num,1);
                        for(var i=1;i<5;i++){
                            var totalReturn=parseInt(unsafeWindow.unitcost["unt"+param3][i])*parseInt(param4)*3600/2;
                            unsafeWindow.seed.resources["city"+param2]["rec"+i][0]=parseInt(unsafeWindow.seed.resources["city"+param2]["rec"+i][0])+totalReturn;
                        }

                    });
                    t.crfil++;
                    ById('Ks_AF_Progression').innerHTML = "<b><i>"+culang.autoTrainDeleteNow+" " + t.crfil+ " / " +t.nbfil +"</i></b>";
                    var numnew = num - 1;
                    if (numnew<fintraitement) {
                        if (numville==Cities.numCities) {
                            ById('Ks_AF_Progression').innerHTML = "<font color=#880000><B>"+culang.autoTrainTournamentNote+"</b></font>";
                            return;
                        }
                        numville++;
                        var cityId = Cities.cities[numville].id;
                        var q = Seed.queue_unt['city'+cityId];
                        numnew=q.length-1;
                        if (q.length<=fintraitement) {
                            ById('Ks_AF_Progression').innerHTML = "<font color=#550000><B>"+culang.autoTrainErrorTryAgain+"</b></font>";
                            return;
                        }
                        setTimeout(function (){
                            t.CancelActionall(numville, numnew, fintraitement);
                        }, (Math.random()*100)+100 );
                    } else {
                        setTimeout(function (){
                            t.CancelActionall(numville, numnew, fintraitement);
                        }, (Math.random()*100)+100 );
                    }

                } else {
                    ById('Ks_AF_Progression').innerHTML = "<font color=#550000><B>"+culang.autoTrainErrorDeleteNotPossible+"</b></font>";
                }
            },
            onFailure: function (rslt) {
                var t = Tabs.AutoTrain;
                ById('Ks_AF_Progression').innerHTML = "<font color=#550000><B>"+culang.autoTrainErrorDeleteNotPossible+"</b></font>";
            }
        });

    },
    AF_CancelAll: function() {
        var t = Tabs.AutoTrain;
        t.nbfil=0;
        t.crfil=0;
        var debutsup = 1;
        if ( ById('Ks_AF_CancelFirst').checked) {
            var debutsup=0 ;
        }
        for(i=0; i<Cities.numCities; i++) {
            var cityId = Cities.cities[i].id;
            var q = Seed.queue_unt['city'+cityId];
            t.nbfil += q.length - debutsup;
        }
        for(i=0; i<Cities.numCities; i++) {
            var cityId = Cities.cities[i].id;
            var q = Seed.queue_unt['city'+cityId];
            if (q.length>debutsup) {
                obj = ById('pbAutoTrainState');
                TrainOptions.Running = false;
                if (obj) obj.value = culang.buttonAutoTrain+" = "+culang.buttonOFF;
                saveTrainingOptions();
                t.CancelActionall(i, q.length-1, debutsup);
                return false;
            }
        }
    },
}
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Train.js">
/************************************************************************************
 *                        KOC POWER - TABS TRAIN                                        *
 ************************************************************************************/
Tabs.Train = {
    tabOrder: TabOptions.toTrain,
    tabLabel: culang.tabLabelTrain,
    cont : null,
    timer : null,
    stats : {},
    selectedCity : {},
    sourceCity : {},
    destinationCity : {},

    show : function (){
        var t = Tabs.Train;
        t.displayCityStats();
        t.changeTroopSelect();
        t.changeDefSelect();

        t.timer = setTimeout (t.show, 4000);
    },

    hide : function (){
        var t = Tabs.Train;
        clearTimeout (t.timer);
    },
    init : function (div){
        var t = Tabs.Train;
        t.cont = div;
        unsafeWindow.KsCancelTraining = t.cancelTrainingNow;
        unsafeWindow.KsCancelDefense = t.cancelDefenseNow;
        s = "<DIV id=trainTopSelect >\
        <DIV class=pdxStat>"+culang.trainHead+"</div><div id=ptTrainStatus style='overflow-y:auto; max-height:70px; text-align:center;'></div><DIV class=pdxEntry>\
        <DIV style='text-align:center;'><b>"+culang.mainCastle+"</b>: &nbsp; <span id=ptspeedcity></span></div>\
        <TABLE class=pdxTab width=100%><TR valign=top><TD width=50%>\
        <TABLE align=center><TR><TD align=right>"+culang.mainTroops+": </td><TD colspan=2>\
        <SELECT id=ptttType>";
            for (r=1; r<16; r++){
                if (r==2) {
                    s+= "<option selected value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
                } else {
                    s+= "<option value='"+r+"'>"+unsafeWindow.unitcost['unt'+r][0]+"</option>";
                }
            }
            if (Seed.items.i36){tutel1=Seed.items.i36}else{tutel1=0};
            if (Seed.items.i37){tutel2=Seed.items.i37}else{tutel2=0};
            if (Seed.items.i38){tutel3=Seed.items.i38}else{tutel3=0};
            if (Seed.items.i26){siege1=Seed.items.i26}else{siege1=0};
            s+= " </select> <br> ("+culang.shortMax+" <span id=ptttSpMax></span>)</td></tr>\
        <TR><TD align=right>"+culang.trainEachSlot+" </td><TD><INPUT id='ptttInpPS' size=5 type='text' value='0'\></td>\
          <TD><INPUT id='ptttButMaxPS' type=submit value='max'\> &nbsp; ("+culang.shortMax+" <span id=ptttSpMaxPS>0</span>)</td></tr>\
        <TR><TD align=right>"+culang.trainSlots+"</td><TD><INPUT id='ptttInpSlots' size=2 type='text' value='1'\></td>\
          <TD width=75%><INPUT id='ptttButMaxSlots' type=submit value='max'\> &nbsp; ("+culang.shortMax+" <span id=ptttSpMaxSlots>1</span>)</td></tr>\
        <TR><TD align=right valign=top>"+culang.autoTrainWorker+": </td><TD colspan=2><INPUT type=CHECKBOX id=chkPop"+ (Options.maxIdlePop?' CHECKED ':'') +">\
        "+culang.mainSpeedups+": <SELECT id=KsGamble>\
        <option value='0'>"+culang.mainNormal+"</option>\
        <option value='1'>5% - 15%</option>\
        <option value='2'>10% - 25%</option>\
        </select>\
        <br><SELECT id=tutelage>\
        <option value='0'><CENTER>-- "+culang.mainSpeedups+" --</center></option>\
        <option value='36'>"+ unsafeWindow.itemlist.i36.name+" ("+tutel1+")</option>\
        <option value='37'>"+ unsafeWindow.itemlist.i37.name+" ("+tutel2+")</option>\
        <option value='38'>"+ unsafeWindow.itemlist.i38.name+" ("+tutel3+")</option>\
        </select>\</td></tr>\
        <TR><TD colspan=3 align=center><DIV style='height:10px'></div><INPUT id='ptttButDo' type=submit value='"+culang.trainNowButton+"'\>\
        <br><span id='expectedTrainTime'>"+culang.trainEST+"</span></td></tr>\
        </table></td><TD width=20></td><TD style='border-left:solid 2px;' width=50% align=center>\
        <TABLE align=center><TR><TD align=right>"+culang.trainDefense+" </td><TD colspan=2>\
      <SELECT id=pttdType>\
        <option value='53'>"+unsafeWindow.fortcost.frt53[0]+"</option>\
        <option value='55'>"+unsafeWindow.fortcost.frt55[0]+"</option>\
        <option value='60'>"+unsafeWindow.fortcost.frt60[0]+"</option>\
        <option value='61'>"+unsafeWindow.fortcost.frt61[0]+"</option>\
        <option value='62'>"+unsafeWindow.fortcost.frt62[0]+"</option>\
      </select> <br> (<span id=pttdSpMax></span>)</td></tr>\
        <TR><TD align=right>"+culang.trainEachSlot+" </td><TD><INPUT id='pttdInpPS' size=5 type='text' value='0'\></td>\
          <TD><INPUT id='pttdButMaxPS' type=submit value='max'\> ("+culang.shortMax+" <span id=pttdSpMaxPS>0</span>)</td></tr>\
        <TR><TD align=right>"+culang.trainSlots+"</td><TD><INPUT id='pttdInpSlots' size=2 type='text' value='1'></td>\
          <TD width=75%><INPUT id='pttdButMaxSlots' type=submit value='max'\> ("+culang.shortMax+" <span id=pttdSpMaxSlots>1</span>)</td></tr>\
        <TR align=center><TD colspan=3><SPAN id=pttdSpace></span></td></tr>\
         <TR><TD colspan=3 align=center><DIV style='height:10px'>\
      <SELECT id=siege>\
      <option value='0'><CENTER>--- "+culang.mainSpeedups+" ---</center></option>\
      <option value='26'>"+ unsafeWindow.itemlist.i26.name+" ("+siege1+")</option>\
      </select></div>\
      <BR><INPUT id='pttdButDo' type=submit value='"+culang.trainDefenseNowButton+"'\>\
      <br><span id='expectedDefenseTime'>"+culang.trainEST+"</span> </td></tr></table>\
        </td></tr></table></div></div>\
        <div style='max-height:"+(Options.HauteurBoite-240)+"px; overflow-y:auto'>\
        <TABLE width=100% class=pdxTab><TR><TD colspan=3><DIV id=divSTtop></div></td></tr>\
        <TR><TD width=70% style='padding-left:5px; padding-right:5px; vertical-align:top;'>\
                <DIV style='text-align:center'>\
                <div class=pdxStat><img title='"+culang.trainCancelAllNote+"' src='"+IMGdeleteButton+"' border=0 id=KsCancelAllTrain1> "+culang.trainTrainHead+" (<SPAN id=statTTtot1></span>)</b></span></div>\
                </div>\
                <DIV id=divSTleft1 style='padding:5px; -moz-box-shadow:inset 0px 0px 5px #000;resize:both; overflow: auto;min-width: 50px;width: 600px; min-height: 1px; max-height:200px; height:150px;'></div>\
                <div id=divST2><br>\
                <DIV style='text-align:center'>\
                <div class=pdxStat><img title='"+culang.trainCancelAllNote+"' src='"+IMGdeleteButton+"' border=0 id=KsCancelAllTrain2> <span id=spType></span>"+culang.trainTrainHead+" (<SPAN id=statTTtot2></span>)</b></span></div>\
                </div>\
                <DIV id=divSTleft2 style='padding:5px; -moz-box-shadow:inset 0px 0px 5px #000;resize:both; overflow: auto;min-width: 50px;width: 600px; min-height: 1px; max-height:60px; height:150px;'></div>\
                </td>\
          <TD width=30% style='padding-left:5px; padding-right:5px; vertical-align:top;'><DIV style='text-align:center'><div  class=pdxStat>"+culang.trainDefenseHead+" (<SPAN id=statDTtot></span>)</b></div></div><DIV id=divSTright style='padding:5px; -moz-box-shadow:inset 0px 0px 5px #000; resize:both; overflow: auto; min-width: 50px; min-height:1px;max-height:"+(Options.HauteurBoite-590)+"px;'></div></td></tr>\
        </div></div></div>";
            t.cont.innerHTML = s;
            t.TTselType = document.getElementById ('ptttType');
            t.TTselType.addEventListener ('change', t.changeTroopSelect, false);
            t.TTinpPerSlot = document.getElementById ('ptttInpPS');            
            t.TTspMax = document.getElementById ('ptttSpMax');
            t.KsGamble = document.getElementById ('KsGamble');
            t.TTspMaxPS = document.getElementById ('ptttSpMaxPS');
            t.TTspMaxSlots = document.getElementById ('ptttSpMaxSlots');
            t.TTbutMaxSlots = document.getElementById ('ptttButMaxSlots');
            t.TTbutMaxPerSlot = document.getElementById ('ptttButMaxPS');
            t.TTinpSlots = document.getElementById ('ptttInpSlots');
            t.TTbutDo = document.getElementById ('ptttButDo');
            t.TDspMax = document.getElementById ('pttdSpMax');
            t.TDspMaxPS = document.getElementById ('pttdSpMaxPS');
            t.TDspMaxSlots = document.getElementById ('pttdSpMaxSlots');
            t.TDbutMaxSlots = document.getElementById ('pttdButMaxSlots');
            t.TDbutMaxPerSlot = document.getElementById ('pttdButMaxPS');
            t.TDinpPerSlot = document.getElementById ('pttdInpPS');
            t.TDinpSlots = document.getElementById ('pttdInpSlots');
            t.TDselType = document.getElementById ('pttdType');
            t.TDbutDo = document.getElementById ('pttdButDo');
            t.TDspSpace = document.getElementById ('pttdSpace');
            t.divTrainStatus = document.getElementById ('ptTrainStatus');
            t.divST2 = document.getElementById ('divST2');
            t.spType = document.getElementById ('spType');
            var dcp = new CdispCityPicker ('ptspeed', ById('ptspeedcity'), true, t.clickCitySelect, 0);
            t.TTinpSlots.addEventListener ('change', t.updateTopTroops, false);
            t.KsGamble.addEventListener ('change', t.changeTroopSelect, false);
            t.TTbutMaxPerSlot.addEventListener ('click', t.clickTroopMaxPS, false);
            t.TTbutMaxSlots.addEventListener ('click', t.clickTroopMaxSlots, false);
            t.TTbutDo.addEventListener ('click', t.clickTroopDo, false);
            t.TDinpSlots.addEventListener ('change', t.updateTopDef, false);
            t.TDselType.addEventListener ('change', t.changeDefSelect, false);
            t.TDbutMaxPerSlot.addEventListener ('click', t.clickDefMaxPS, false);
            t.TDbutMaxSlots.addEventListener ('click', t.clickDefMaxSlots, false);
            t.TDbutDo.addEventListener ('click', t.clickDefDo, false);
            document.getElementById ('KsCancelAllTrain1').addEventListener ('click', function() {t.CancelAllTraining(false);}, false);
            document.getElementById ('KsCancelAllTrain2').addEventListener ('click', function() {t.CancelAllTraining(true);}, false);
            document.getElementById ('chkPop').addEventListener ('change', t.clickCheckIdlePop, false);

    },

    /*******  TROOPS  ******/
    updateTopTroops : function (){
        var t = Tabs.Train;
        var slots = parseInt(t.TTinpSlots.value, 10);
        var id = t.TTselType.value;
        if (isNaN(slots) || slots<0)
            slots = 0;
        t.TTspMax.innerHTML = t.stats.MaxTrain;
        if (id <=12)
            t.TTspMaxSlots.innerHTML = t.stats.barracks1 - t.stats.queued1;
        else 
            t.TTspMaxSlots.innerHTML = t.stats.barracks2 - t.stats.queued2;
            
        if (slots<1 || 
                (t.stats.barracks1-t.stats.queued1 < 1 && id <=12) || 
                (t.stats.barracks2-t.stats.queued2 < 1 && id >12))
            t.TTspMaxPS.innerHTML = 0;
        else
            t.TTspMaxPS.innerHTML = parseInt(t.stats.MaxTrain / slots);
    },


    clickTroopMaxPS : function (){
        var t = Tabs.Train;
        var slots = parseInt(t.TTinpSlots.value, 10);
        var id = t.TTselType.value;
        if (slots<1 || 
                (t.stats.barracks1-t.stats.queued1 < 1 && id <=12) || 
                (t.stats.barracks2-t.stats.queued2 < 1 && id >12))
            t.TTinpPerSlot.value = 0;
        else
            t.TTinpPerSlot.value = parseInt(t.stats.MaxTrain / slots);
    },

    clickTroopMaxSlots : function (){
        var t = Tabs.Train;
        var id = t.TTselType.value;
        if (id <=12)
            t.TTinpSlots.value = t.stats.barracks1 - t.stats.queued1;
        else 
            t.TTinpSlots.value = t.stats.barracks2 - t.stats.queued2;
    },

    clickCitySelect : function (city){
        var t = Tabs.Train;
        t.selectedCity = city;
        t.lastQueString1 = null;
        t.lastQueString2 = null;
        t.lastDQueString = null;
        t.displayCityStats ();
        t.changeTroopSelect();
        t.changeDefSelect();
    },

    clickCheckIdlePop : function (){
        var t = Tabs.Train;
        if (document.getElementById ('chkPop').checked)
            Options.maxIdlePop = true;
        else
            Options.maxIdlePop = false;
        saveOptions ();
        t.displayCityStats ();
        t.changeTroopSelect ();
    },
    
    limitingFactor : null,
    
    changeTroopSelect : function (){
        var t = Tabs.Train;
        var cityId = t.selectedCity.id;
        var id = t.TTselType.value;
        t.lastTroopSelect = id;
        t.limitingFactor = null;
        var uc = unsafeWindow.unitcost['unt'+id];
        var a=1
        var gumble= t.KsGamble.value;
        if (gumble==0) a=1;
        if (gumble==1) a=2;
        if (gumble==2) a=4;
        var max = 9999999999;
        if ( (t.stats.food / (uc[1]*a)) < max){
            max = t.stats.food / (uc[1]*a);
            t.limitingFactor = 'food';
        }
        if ( (t.stats.wood / (uc[2]*a)) < max){
            max = t.stats.wood / (uc[2]*a);
            t.limitingFactor = 'wood';
        }
        if ( (t.stats.stone / (uc[3]*a)) < max){
            max = t.stats.stone / (uc[3]*a);
            t.limitingFactor = 'stone';
        }
        if ( (t.stats.ore / (uc[4]*a)) < max){
            max = t.stats.ore / (uc[4]*a);
            t.limitingFactor = 'ore';
        }
        if ( (t.stats.idlePop / uc[6]) < max){
            max = t.stats.idlePop / (uc[6]);
            t.limitingFactor = 'pop';
        }
        t.stats.MaxTrain = parseInt (max);
        if (t.stats.MaxTrain < 0)
            t.stats.MaxTrain = 0;
        if (matTypeof(uc[8]) == 'object'){
            for (k in uc[8]){
                var b = getCityBuilding (cityId, k.substr(1));
                if (b.maxLevel < uc[8][k][1]){
                    t.stats.MaxTrain = 0;
                    t.limitingFactor = null;
                    break;
                }
            }
        }
        if (matTypeof(uc[9]) == 'object'){
            for (k in uc[9]){
                if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
                    t.stats.MaxTrain = 0;
                    t.limitingFactor = null;
                    break;
                }
            }
        }
        t.updateTopTroops();
    },

    clickTroopDo : function (){
        var t = Tabs.Train;
        var cityId = t.selectedCity.id;
        unsafeWindow.citysel_click(ById('citysel_'+ (t.selectedCity.idx+1)+''));
        var unitId = t.TTselType.value;
        var perSlot = parseInt(t.TTinpPerSlot.value, 10);
        var numSlots = parseInt(t.TTinpSlots.value, 10);

        t.displayCityStats ();
        if (perSlot<1){
            t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainNoSlotsNote+'</font>';
            return;
        }
        if (perSlot*numSlots > t.stats.MaxTrain){
            t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainTroopAmountNote+' '+ t.stats.MaxTrain +' '+culang.trainTroopAmountNote2+'</font>';
            return;
        }
        if (numSlots<1 || numSlots>t.stats.barracks - t.stats.queued){
            t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainWrongSlotsNote+'</font>';
            return;
        }

        var tut = document.getElementById ('tutelage').value;
        var gam = t.KsGamble.value;
        t.setBusy(true);
        var que = [];
        for (var i=0; i<numSlots; i++)
            que.push (['T', unitId, parseInt (perSlot)]);
        t.divTrainStatus.innerHTML = '';
        t.doQueue (cityId, tut, gam, que);
    },


    /*******  DEF  ******/

    updateTopDef : function (){
        var t = Tabs.Train;
        var slots = parseInt(t.TDinpSlots.value, 10);
        if (isNaN(slots) || slots<0)
            slots = 0;
        t.TDspMax.innerHTML = ''+culang.shortMax+' '+ t.stats.MaxDefTrain +'&nbsp; '+culang.trainOwned+':'+ t.stats.defOwned;
        t.TDspMaxSlots.innerHTML = t.stats.wallLevel-t.stats.Dqueued;
        if (slots<1)
            t.TDspMaxPS.innerHTML = 0;
        else
            t.TDspMaxPS.innerHTML = parseInt(t.stats.MaxDefTrain / slots);

        t.TDspSpace.innerHTML = '<table border=1 cellspacing=0 width=100% bordercolor=black><tr><td>'+uW.g_js_strings.commonstr.level+'</td><td>'+culang.trainWallDefense+'</td><td>'+culang.trainFieldDefense+'</td></tr>\
       <tr><td><B>'+ t.stats.wallLevel +'</b></td><td>'+ (t.stats.wallSpaceUsed+t.stats.wallSpaceQueued)  +'/<B>'+ t.stats.wallSpace +'</b></td>\
        <td>'+ (t.stats.fieldSpaceUsed+t.stats.fieldSpaceQueued) +'/<B>'+ t.stats.fieldSpace +'</b></td></table>';
    },

    changeDefSelect : function (){
        var t = Tabs.Train;
        var cityId = t.selectedCity.id;
        var id = t.TDselType.value;
        t.lastDefSelect = id;
        t.stats.defOwned = parseInt(Seed.fortifications['city' + cityId]['fort'+id]);
        var uc = unsafeWindow.fortcost['frt'+id];
        var max = 9999999999;
        if ( (t.stats.food / uc[1]) < max)
            max = t.stats.food / uc[1];
        if ( (t.stats.wood / uc[2]) < max)
            max = t.stats.wood / uc[2];
        if ( (t.stats.stone / uc[3]) < max)
            max = t.stats.stone / uc[3];
        if ( (t.stats.ore / uc[4]) < max)
            max = t.stats.ore / uc[4];
        if ( (t.stats.idlePop / uc[6]) < max)
            max = t.stats.idlePop / uc[6];
        t.stats.MaxDefTrain = parseInt (max);
        if (t.stats.MaxDefTrain < 0)
            t.stats.MaxDefTrain = 0;
        if (matTypeof(uc[8]) == 'object'){
            for (k in uc[8]){
                var b = getCityBuilding (cityId, k.substr(1));
                if (b.maxLevel < uc[8][k][1]){
                    t.stats.MaxDefTrain = 0;
                    break;
                }
            }
        }
        if (matTypeof(uc[9]) == 'object'){
            for (k in uc[9]){
                if (parseInt(Seed.tech['tch'+k.substr(1)]) < uc[9][k][1]){
                    t.stats.MaxDefTrain = 0;
                    break;
                }
            }
        }

        var spaceEach = parseInt(unsafeWindow.fortstats["unt"+ id][5]);
        if (id<60)
            var spaceAvail = t.stats.wallSpace - t.stats.wallSpaceUsed - t.stats.wallSpaceQueued;
        else
            var spaceAvail = t.stats.fieldSpace - t.stats.fieldSpaceUsed - t.stats.fieldSpaceQueued;
        if ( t.stats.MaxDefTrain * spaceEach > spaceAvail)
            t.stats.MaxDefTrain = parseInt(spaceAvail / spaceEach);

        t.updateTopDef();
    },

    clickDefMaxPS : function (){
        var t = Tabs.Train;
        var slots = parseInt(t.TDinpSlots.value, 10);
        if (slots<1)
            t.TDinpPerSlot.value = 0;
        else
            t.TDinpPerSlot.value = parseInt(t.stats.MaxDefTrain / slots);
    },

    clickDefMaxSlots : function (){
        var t = Tabs.Train;
        t.TDinpSlots.value = t.stats.wallLevel-t.stats.Dqueued;
    },

    clickDefDo : function (){
        var t = Tabs.Train;
        var cityId = t.selectedCity.id;
        var unitId = t.TDselType.value;
        var perSlot = parseInt(t.TDinpPerSlot.value, 10);
        var numSlots = parseInt(t.TDinpSlots.value, 10);

        t.displayCityStats ();
        if (perSlot<1){
            t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainZeroTroopsNote+'</font>';
            return;
        }
        if (perSlot*numSlots > t.stats.MaxDefTrain){
            t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainDefAmountNote+' '+ t.stats.MaxDefTrain +' '+culang.trainDefAmountNote2+'</font>';
            return;
        }
        if (numSlots<1 || numSlots > t.stats.wallLevel-t.stats.Dqueued){
            t.divTrainStatus.innerHTML = '<FONT COLOR=#550000>'+culang.trainWrongSlotsNote+'</font>';
            return;
        }
        var siege = document.getElementById ('siege').value;
        t.setBusy(true);
        var que = [];
        for (var i=0; i<numSlots; i++)
            que.push (['T', unitId, parseInt (perSlot)]);
        t.divTrainStatus.innerHTML = '';
        t.doDefQueue (cityId, siege, que);
    },

    doDefQueue : function (cityId, siege, que, errMsg){
        var t = Tabs.Train;
        try {
            t.displayCityStats();
            if (errMsg){
                t.dispTrainStatus ('<font color=#550000><B>'+culang.mainError+': '+ errMsg +'</b></font><BR>');
                t.setBusy(false);
                return;
            }
            var cmd = que.shift();
            if (!cmd){
                t.dispTrainStatus ('<B>'+culang.trainDoDefQueue+'</b><BR>');
                t.setBusy(false);
                return;
            }
            if (cmd[0] == 'T'){
                t.dispTrainStatus (''+culang.trainDefStatus+' <span class="boldRed">'+ cmd[2] +'</span> '+  fortNamesShort[cmd[1]] +' '+culang.trainDefStatus2+'<BR>');
                doDefTrain ( cityId, siege, cmd[1], cmd[2],
                    function(errMsg){
                        setTimeout(function (){Tabs.Train.doDefQueue(cityId, siege, que, errMsg);}, (Math.random()*3500)+500);
                    } );
            }
        } catch (err) {
            t.dispTrainStatus ('<font color=#550000>'+culang.mainError+': '+ err.message +'</font><BR>');
            t.setBusy(false);
        }
    },
    setBusy : function (tf){
        var t = Tabs.Train;
        t.TDbutDo.disabled = tf;
        t.TTbutDo.disabled = tf;
    },
    fixQueTimes : function (q){
        var now = unixTime();
        if (q[0][2] > now)
            q[0][2] = now;
        for (var i=0; i<q.length; i++){
            if (q[i+1]!=null && q[i+1][2]!=q[i][3])
                q[i][3] = q[i+1][2];
        }
    },
    displayCityStats : function (){
        var t = Tabs.Train;
        try {
        var cityId = t.selectedCity.id;
        t.stats.food = parseInt (Seed.resources['city'+cityId].rec1[0]/3600);
        t.stats.wood = parseInt (Seed.resources['city'+cityId].rec2[0]/3600);
        t.stats.stone = parseInt (Seed.resources['city'+cityId].rec3[0]/3600);
        t.stats.ore = parseInt (Seed.resources['city'+cityId].rec4[0]/3600);
        t.stats.gold = Seed.citystats['city'+cityId].gold[0];
        if (Options.maxIdlePop)
            t.stats.idlePop = parseInt(Seed.citystats['city'+cityId].pop[0]);
        else
            t.stats.idlePop = parseInt(Seed.citystats['city'+cityId].pop[0]) - parseInt(Seed.citystats['city'+cityId].pop[3]);
        t.stats.barracks1 = getCityBuilding (cityId, 13).count;
        var asc = false;
        var asct = 0;
        if (Seed.cityData.city[cityId].isPrestigeCity) {
            asc = true;
            asct = Seed.cityData.city[cityId].prestigeInfo.prestigeType;
        }
        if (asct == 1) { //Druid
            t.stats.barracks2 = getCityBuilding (cityId, 22).count;
            t.spType.innerHTML = culang.ascDruid;
        } else if (asct == 2) { //Fey
            t.stats.barracks2 = getCityBuilding (cityId, 24).count;
            t.spType.innerHTML = culang.ascFey;
        } else if (asct == 3) { //Briton 
            t.stats.barracks2 = getCityBuilding (cityId, 26).count;
            t.spType.innerHTML = culang.ascBriton;
        } else {
            //Normale Stadt
        }
        if (asc) {
            t.divST2.style.display = "block";
        } else {
            t.divST2.style.display = "none";
        }
        cost = unsafeWindow.unitcost['unt'+t.TTselType.value];
        nbunit=t.TTinpPerSlot.value*t.TTinpSlots.value;
        var a=1;
        var gumble= t.KsGamble.value;
        if (gumble==0) a=1;
        if (gumble==1) a=2;
        if (gumble==2) a=4;
        consoFood = cost[1] * a * nbunit;
        styleFood="";stylePop="";styleWood="";styleOre="";styleStone="";
        if (consoFood>t.stats.food) styleFood='style="color:#E30;font-weight:bold;"';
        consoOre = cost[4] * a * nbunit;
        if (consoOre>t.stats.ore) styleOre='style="color:#E30;font-weight:bold;"';
        consoStone = cost[3] * a * nbunit;
        if (consoStone>t.stats.stone) styleStone='style="color:#E30;font-weight:bold;"';
        consoWood = cost[2] * a * nbunit;
        if (consoWood>t.stats.wood) styleWood='style="color:#E30;font-weight:bold;"';
        consoPop = cost[6] * nbunit;
        if (consoPop>t.stats.idlePop) stylePop='style="color:#E30;font-weight:bold;"';

        var m = '<DIV class=pdxStat2>'+culang.mainTroopAmount+'</div>';
        m += '<TABLE class=pdxTab width=100%><TR align=center>';
        for (var i = 1; i<16; i++) {
            m+='<TD width=6.6%><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+i+'_30_s34.jpg" title="'+unsafeWindow.unitcost['unt'+i][0]+'"></td>';
        }
        m+= '</tr><TR align=center>';
        for (var i = 1; i<16; i++) {
            m+= '<TD>'+addCommas(parseIntNan(Seed.units['city'+cityId]['unt'+i]))+'</td>';
        }
        m+= '</tr></table>';
        m += '<DIV class=pdxStat2>'+culang.mainRessources+'</div>';
        m += '<TABLE class=pdxTab width=100%><TR align=center>\
        <td width=15%>&nbsp;</td><TD width=14%><B>'+unsafeWindow.g_js_strings.commonstr.gold+'</b></td><TD width=15%><B>'+unsafeWindow.g_js_strings.commonstr.food+'</b></td><TD width=14%><B>'+unsafeWindow.g_js_strings.commonstr.wood+'</b></td><TD width=14%><B>'+unsafeWindow.g_js_strings.commonstr.stone+'</b></td><TD width=14%><B>'+unsafeWindow.g_js_strings.commonstr.ore+'</b></td><TD width=14%><B>'+unsafeWindow.g_js_strings.showPopTooltip.idlepop+'</b></td></tr>\
        <TR align=center><td><b><u>'+culang.mainInventory+'</u></b></td><TD><SPAN id=ptttr_gold>'+ UniteKMG(t.stats.gold) +'</span></td><TD><SPAN id=ptttr_food>'+ UniteKMG(t.stats.food) +'</span></td>\
        <TD><SPAN id=ptttr_wood>'+ UniteKMG(t.stats.wood) +'</span></td><TD><SPAN id=ptttr_stone>'+ UniteKMG(t.stats.stone) +'</span></td><TD><SPAN id=ptttr_ore>'+ UniteKMG(t.stats.ore) +'</span></td>\
        <TD><SPAN id=ptttr_gold>'+ addCommasInt(t.stats.idlePop) +'</span></td></tr>\
        <tr align=center><td width=15%><span class="boldRed">'+culang.mainNeed+'</span></td><td>&nbsp;</td><td '+styleFood+'>'+UniteKMG(consoFood)+'</td><td '+styleWood+'>'+UniteKMG(consoWood)+'</td><td '+styleStone+'>'+UniteKMG(consoStone)+'</td><td '+styleOre+'>'+UniteKMG(consoOre)+'</td>\
        <TD '+stylePop+'>'+ addCommasInt(consoPop)+'</td></tr>\
        </table>';

        document.getElementById ('divSTtop').innerHTML = m;
        var e=parseInt((t.TDinpPerSlot.value*t.TDinpSlots.value),10);
        if (e>0) {
            d=t.TDselType.value;
            var a=WallsTrainTime(d,e,cityId);
            var reduction=0
            var tut = ById('siege').value;
            if (tut==26) reduction=parseInt(a*0.3);
            var reducStr=timestr(reduction,1);
            ById('expectedDefenseTime').innerHTML=culang.trainEST+" <b>" + timestr(a,1) +"</b>";
            if (reduction>0) {
                var totalred = a - reduction;
                ById('expectedDefenseTime').innerHTML=culang.trainEST+" <b>" + timestr(totalred,1) +"</b>";
                ById('expectedDefenseTime').title=culang.trainEST+" " + timestr(a,1) +" - "+culang.trainESTreduction+": " + reducStr + "";
            }
        }
        var e=parseInt(nbunit,10);
        var b=t.TTselType.value;
        var selunit = b;
        if (e>0) {
            var m = TroopTrainTime(b, e, cityId);
                
            var reduction=0
            var tut = document.getElementById ('tutelage').value;
            if (tut==36)
                reduction=parseInt(m*0.3,10);
            if (tut==37)
                reduction=parseInt(m*0.5,10);
            if (tut==38)
                reduction=parseInt(m*0.7,10);

            var reducStr=timestr(reduction,1);

            var aa=1;
            var now = unixTime();
            var estimfin = new Date();
            estimfin.setTime((now+m) * 1000);
            ById('expectedTrainTime').innerHTML=culang.trainEST+" <b>" + timestr(m,1) +"</b><br>"+culang.trainTimeExpected+" "+estimfin.toLocaleString()+"";
            var gumble= t.KsGamble.value;
            if (gumble==0) aa=1;
            if (gumble==1) aa=2;
            if (gumble==2) aa=4;
            if (aa>1 && reduction==0) {
                if (aa==2) {
                    var r1=parseInt(m*0.05,10);
                    var r2=parseInt(m*0.15,10);
                    var n1 = m - r1;
                    var n2 = m - r2;
                }
                if (aa==4) {
                    var r1=parseInt(m*0.10,10);
                    var r2=parseInt(m*0.25,10);
                    var n1 = m - r1;
                    var n2 = m - r2;
                }
                var now = unixTime();
                var estimfin1 = new Date();
                estimfin1.setTime((now+n2) * 1000);
                var estimfin2 = new Date();
                estimfin2.setTime((now+n1) * 1000);
                ById('expectedTrainTime').innerHTML=culang.trainEST+" "+culang.trainESToutput+" <b><font color=red>" + timestr(n2,1) +"</font> "+culang.trainESToutput2+" <font color=red>" + timestr(n1,1) +"</font></b><br>"+culang.trainTimeExpected+" "+culang.trainESToutput3+" "+estimfin1.toLocaleString()+"<br>"+culang.trainESToutput4+" "+estimfin2.toLocaleString()+"";
            }
            if (reduction>0 && aa==1) {
                var totalred = m - reduction;
                var now = unixTime();
                var estimfin = new Date();
                estimfin.setTime((now+totalred) * 1000);
                ById('expectedTrainTime').innerHTML=culang.trainEST+" <b><font color=red>" + timestr(totalred,1) +"</font></b><br>"+culang.trainTimeExpected+" "+estimfin.toLocaleString()+"";
                ById('expectedTrainTime').title=culang.trainEST+" " + timestr(m,1) +" - "+culang.trainESTreduction+": " + reducStr + "";
            }
            if (reduction>0 && aa>1) {
                var totalred = m - reduction;
                if (aa==2) {
                    var r1=parseInt(totalred*0.05,10);
                    var r2=parseInt(totalred*0.15,10);
                    var n1 = totalred - r1;
                    var n2 = totalred - r2;
                }
                if (aa==4) {
                    var r1=parseInt(totalred*0.10,10);
                    var r2=parseInt(totalred*0.25,10);
                    var n1 = totalred - r1;
                    var n2 = totalred - r2;
                }

                var now = unixTime();
                var estimfin1 = new Date();
                estimfin1.setTime((now+n2) * 1000);
                var estimfin2 = new Date();
                estimfin2.setTime((now+n1) * 1000);
                ById('expectedTrainTime').innerHTML=culang.trainEST+" <b>"+culang.trainESToutput+" <font color=red>" + timestr(n2,1) +"</font> "+culang.trainESToutput2+" <font color=red>" + timestr(n1,1) +"</font></b><br>"+culang.trainTimeExpected+" <u>"+culang.trainESToutput3+"</u>  "+estimfin1.toLocaleString()+"<br><u>"+culang.trainESToutput4+"</u> "+estimfin2.toLocaleString()+"";
            }
        }
        var totTime = 0;
        var q = Seed.queue_unt['city'+cityId];
        var c = Cities.byID[cityId].idx;
        t.stats.q1 = [];
        t.stats.q2 = [];
        t.stats.queued1 = 0;
        t.stats.queued2 = 0;
        for (var i=0; i< q.length; i++) {
            var qe = q[i];
            qe[8] = i;
            if (qe[7]) {
                t.stats.queued2++;
                t.stats.q2.push(qe);
            } else {
                t.stats.queued1++;
                t.stats.q1.push(qe);
            }
        }
        var qs1 = t.stats.q1.toString();
        var qs2 = t.stats.q2.toString();
        var now = unixTime();
        
        //Warteschlange 1
        if (t.stats.q1.length>0)
            totTime1 = t.stats.q1[t.stats.q1.length-1][3] - now;
        else 
            totTime1 = 0;
        if (qs1 == t.lastQueString1){
            if (t.stats.q1.length>0){
                var cur = t.stats.q1[0][3] - now;
                if (cur < 1)
                    t.stats.q1.shift();
                if (document.getElementById ('ptttfq1')) document.getElementById ('ptttfq1').innerHTML = timestr(cur, true);
            }
        } else {
            t.lastQueString1 = qs1;
            t.stats.queued1 = 0;
            m = '<TABLE align=center class=pdxTab>';
            if (t.stats.q1.length>0 ){
                t.fixQueTimes (t.stats.q1);
                t.stats.queued1 = t.stats.q1.length;
                first = true;
                for (var i=0; i<t.stats.q1.length; i++){
                    start = t.stats.q1[i][2];
                    end = t.stats.q1[i][3];
                    if (first)
                        actual = end - now;
                    else
                        actual = end - lastEnd;
                    if (actual < 0)
                        actual = 0;
                        
                    param1=t.stats.q1[i][8]; // 
                    param2=cityId; // id de la ville
                    param3=t.stats.q1[i][0]; // Type de trouoe
                    param4=t.stats.q1[i][1]; // Qte troupe
                    param5=end; // debut
                    param6=start; // fin
                    param7=actual; // duree
                    m += '<TR align=right><td width=35 align=center>'+(i+1)+'&nbsp;<a onclick="KsCancelTraining('+param1+','+param2+','+param3+','+param4+','+param5+','+param6+','+param7+');return false;" href="javascript:void(0);"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.trainDelete+'"></a></td><TD>'+ t.stats.q1[i][1] +' </td><TD align=left> '+ unsafeWindow.unitcost['unt'+t.stats.q1[i][0]][0].replace(''+culang.mainRallyPoint+'','');
                    if (first)
                        m += '</td><TD>&nbsp;<img src="'+IMGwaiting+'" onclick=citysel_click(document.getElementById(\'citysel_'+ (c+1)+'\'));modal_speedup("trn",'+param3+','+param3+',"Training",'+param6+');return false;> &nbsp; '+  timestr(end-start, true) +'</td><TD> (<SPAN id=ptttfq1>'+ timestr(actual, true) +'</span>)';
                    else
                        m += '</td><TD> &nbsp; '+  timestr(actual, true) +'</td></tr>';
                    lastEnd = end;
                    first = false;
                }
            }
            m += '</table>';
            document.getElementById ('divSTleft1').innerHTML = m;
        }
        m = t.stats.barracks1 +' '+culang.trainCasernes+'';
        if (t.stats.queued1 > 0)
            m += ', '+ t.stats.queued1 +' '+culang.mainSlots+'';
        if (totTime1 > 0)
            m += ', '+ unsafeWindow.timestr(totTime1);
        document.getElementById ('statTTtot1').innerHTML = m;
        
        //Warteschlange 2
        if (t.stats.q2.length>0)
            totTime2 = t.stats.q2[t.stats.q2.length-1][3] - now;
        else 
            totTime2 = 0;
        if (qs2 == t.lastQueString2){
            if (t.stats.q2.length>0){
                var cur = t.stats.q2[0][3] - now;
                if (cur < 1)
                    t.stats.q2.shift();
                if (document.getElementById ('ptttfq2')) document.getElementById ('ptttfq2').innerHTML = timestr(cur, true);
            }
        } else {
            t.lastQueString2 = qs2;
            t.stats.queued2 = 0;
            m = '<TABLE align=center class=pdxTab>';
            if (t.stats.q2.length>0 ){
                t.fixQueTimes (t.stats.q2);
                t.stats.queued2 = t.stats.q2.length;
                first = true;
                for (var i=0; i<t.stats.q2.length; i++){
                    start = t.stats.q2[i][2];
                    end = t.stats.q2[i][3];
                    if (first)
                        actual = end - now;
                    else
                        actual = end - lastEnd;
                    if (actual < 0)
                        actual = 0;
                    param1=t.stats.q2[i][8]; // 
                    param2=cityId; // id de la ville
                    param3=t.stats.q2[i][0]; // Type de trouoe
                    param4=t.stats.q2[i][1]; // Qte troupe
                    param5=end; // debut
                    param6=start; // fin
                    param7=actual; // duree
                    m += '<TR align=right><td width=35 align=center>'+(i+1)+'&nbsp;<a onclick="KsCancelTraining('+param1+','+param2+','+param3+','+param4+','+param5+','+param6+','+param7+');return false;" href="javascript:void(0);"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.trainDelete+'"></a></td><TD>'+ t.stats.q2[i][1] +' </td><TD align=left> '+ unsafeWindow.unitcost['unt'+t.stats.q2[i][0]][0].replace(''+culang.mainRallyPoint+'','');
                    if (first)
                        m += '</td><TD>&nbsp;<img src="'+IMGwaiting+'" onclick=citysel_click(document.getElementById(\'citysel_'+ (c+1)+'\'));modal_speedup("trn",'+param3+','+param3+',"Training",'+param6+');return false;> &nbsp; '+  timestr(end-start, true) +'</td><TD> (<SPAN id=ptttfq2>'+ timestr(actual, true) +'</span>)';
                    else
                        m += '</td><TD> &nbsp; '+  timestr(actual, true) +'</td></tr>';
                    lastEnd = end;
                    first = false;
                }
            } 
            m += '</table>';
            document.getElementById ('divSTleft2').innerHTML = m;
        }
        m = t.stats.barracks2 +' '+culang.trainCasernes+'';
        if (t.stats.queued2 > 0)
            m += ', '+ t.stats.queued2 +' '+culang.mainSlots+'';
        if (totTime2 > 0)
            m += ', '+ unsafeWindow.timestr(totTime2);
        document.getElementById ('statTTtot2').innerHTML = m;
        
        
        getWallInfo (cityId, t.stats);
        var totTime = 0;
        var q = Seed.queue_fort['city'+cityId];
        var qs = q.toString();
        if (q!=null && q.length>0)
            totTime = q[q.length-1][3] - now;
        if ( qs == t.lastDQueString){
            if (q!=null && q.length>0){
                var cur = q[0][3] - now;
                if (cur < 1)
                    q.shift();
                document.getElementById ('pttdfq').innerHTML = timestr(cur, true);
            }
        } else {
            t.lastDQueString = qs;
            t.stats.Dqueued = 0;
            t.stats.wallSpaceQueued = 0;
            t.stats.fieldSpaceQueued = 0;
            m = '<TABLE align=center class=pdxTab>';
            if (q!=null && q.length > 0 ){
                t.fixQueTimes (q);
                t.stats.Dqueued = q.length;
                first = true;
                for (i=0; i<q.length; i++){
                    if (q[i][0] < 60)
                        t.stats.wallSpaceQueued += parseInt(unsafeWindow.fortstats["unt"+ q[i][0]][5]) * parseInt(q[i][1]);
                    else
                        t.stats.fieldSpaceQueued += parseInt(unsafeWindow.fortstats["unt"+ q[i][0]][5]) * parseInt(q[i][1]);
                    start = q[i][2];
                    end = q[i][3];
                    if (first)
                        actual = end - now;
                    else
                        actual = end - lastEnd;
                    if (actual < 0)
                        actual = 0;
                    q[i][7]=cityId;
                    m += '<TR align=right><TD><a onclick="KsCancelDefense('+ q[i][0]+','+q[i][1]+','+q[i][2]+','+q[i][3]+','+q[i][5]+','+q[i][6]+','+q[i][7] +','+ i +');return false;" href="javascript:void(0);"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.trainDeleteDefenseNote+'"></a></td><TD>'+ q[i][1] +'</td><TD align=left> '+ fortNamesShort[q[i][0]];
                    if (first)
                        m += '</td><TD> &nbsp; '+  timestr(end-start, true) +'</td><TD> (<SPAN id=pttdfq>'+ timestr(actual, true) +'</span>)';
                    else
                        m += '</td><TD> &nbsp; '+  timestr(actual, true) +'</td></tr>';
                    lastEnd = end;
                    first = false;
                }
            }
            m += '</table>';
            document.getElementById ('divSTright').innerHTML = m;
        }
        m = t.stats.Dqueued +' '+culang.mainSlots+'';
        if (totTime > 0)
            m += ', '+ unsafeWindow.timestr(totTime);
        document.getElementById ('statDTtot').innerHTML = m;
        } catch (ex) {alert(ex.name +': '+ ex.message + " @"+ ex.lineNumber);}
    },
    dispTrainStatus : function (msg){
        var t = Tabs.Train;
        t.divTrainStatus.innerHTML = msg + t.divTrainStatus.innerHTML;
    },
    CancelActionall: function(cityId, num, fintraitement, type) {
        var t = Tabs.Train;
try {        
        var q = Seed.queue_unt['city'+cityId];
        var isPrestigeQueue = Seed.queue_unt["city"+cityId][num][7];
        if (type != isPrestigeQueue) {
            var numnew = num - 1;
            if (numnew<fintraitement) {
                t.dispTrainStatus ('<font color=#550000><B>'+culang.trainDeleteMoreTrain+'</b></font><BR>');
                document.getElementById ('KsCancelAllTrain1').style.display='inline';
                document.getElementById ('KsCancelAllTrain2').style.display='inline';
                t.displayCityStats();
            } else {
                setTimeout(function (){
                    t.CancelActionall(cityId, numnew, fintraitement, type);
                }, (Math.random()*200)+150);
            }
        }
        var now = unixTime();
        start = q[num][2];
        end = q[num][3];
        if (first)
            actual = end - now;
        else
            actual = end - lastEnd;
        if (actual < 0)
            actual = 0;
        var param2=cityId; // id de la ville
        var param3=q[num][0]; // Type de trouoe
        var param4=q[num][1]; // Qte troupe
        var param5=end; // debut
        var param6=start; // fin
        var param7=actual; // duree
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cityId = param2;
        params.requestType ="CANCEL_TRAINING";
        params.numtrptrn = param4;
        params.trnETA= param5;
        params.trnNeeded = param7;
        params.trnTmp = param6;
        params.typetrn= param3;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelTraining.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                var t = Tabs.Train;
                if (rslt.ok) {
                    
                        var k=0;
                        var isPrestigeQueue = Seed.queue_unt["city"+param2][num][7];
                        for(var j=0;j<Seed.queue_unt["city"+param2].length;j++){
                            if(j>num && (Seed.queue_unt["city" + param2][j][7] === isPrestigeQueue)){
                                Seed.queue_unt["city"+param2][j][2]=parseInt(rslt.dateTraining[k]["start"]);
                                Seed.queue_unt["city"+param2][j][3]=parseInt(rslt.dateTraining[k]["end"]);
                                k++;
                            }
                        }
                        Seed.queue_unt["city"+param2].splice(num,1);
                        for(var i=1;i<5;i++){
                            var totalReturn=parseInt(uW.unitcost["unt"+param3][i])*parseInt(param4)*3600/2;
                            Seed.resources["city"+param2]["rec"+i][0]=parseInt(Seed.resources["city"+param2]["rec"+i][0])+totalReturn;
                        }
                
                    
                    var numnew = num - 1;
                    if (numnew<fintraitement) {
                        t.dispTrainStatus ('<font color=#550000><B>'+culang.trainDeleteMoreTrain+'</b></font><BR>');
                        document.getElementById ('KsCancelAllTrain1').style.display='inline';
                        document.getElementById ('KsCancelAllTrain2').style.display='inline';
                        t.displayCityStats();
                    } else {
                        setTimeout(function (){
                            t.CancelActionall(cityId, numnew, fintraitement, type);
                        }, (Math.random()*200)+150);
                    }

                } else {
                    t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorDelete+"</b></font><BR>");
                    t.displayCityStats();
                    document.getElementById ('KsCancelAllTrain1').style.display='inline';
                    document.getElementById ('KsCancelAllTrain2').style.display='inline';
                }
            },
            onFailure: function (rslt) {
                var t = Tabs.Train;
                t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+":  "+culang.trainErrorDelete+"</b></font><BR>");
                t.displayCityStats();
                document.getElementById ('KsCancelAllTrain1').style.display='inline';
                document.getElementById ('KsCancelAllTrain2').style.display='inline';
            }
        });
} catch (ex) {
    alert(ex.name +': '+ ex.message + " @"+ ex.lineNumber);
}
    },
    CancelAllTraining : function(type) {
        var t = Tabs.Train;
try {
        var cityId = t.selectedCity.id;
        var q = Seed.queue_unt['city'+cityId];
        t.stats.q1 = [];
        t.stats.q2 = [];
        t.stats.queued1 = 0;
        t.stats.queued2 = 0;
        for (var i=0; i< q.length; i++) {
            var qe = q[i];
            qe[8] = i;
            if (qe[7]) {
                t.stats.queued2++;
                t.stats.q2.push(qe);
            } else {
                t.stats.queued1++;
                t.stats.q1.push(qe);
            }
        }
        if (type) {
            var q = t.stats.q2;
        } else {
            var q = t.stats.q1;
        }
        if (q.length>0) {
            var b=prompt(""+culang.trainDeleteMore+" "+(q.length)+""+culang.trainDeleteMore2+"", 2);
            if (parseInt(b)<=q.length && parseInt(b)>0) {
                t.dispTrainStatus ('<font color=#550000><B>'+culang.trainDeleteNow+'</b></font><BR>');
                document.getElementById ('KsCancelAllTrain1').style.display='none';
                document.getElementById ('KsCancelAllTrain2').style.display='none';
                obj = ById('pbAutoTrainState');
                TrainOptions.Running = false;
                if (obj) obj.value = culang.buttonAutoTrain+" = "+culang.buttonOFF;
                saveTrainingOptions();
                t.CancelActionall(cityId, q[q.length-1][8], q[b-1][8], type);
            }
        }
} catch (ex) {
    alert(ex.name +': '+ ex.message + " @"+ ex.lineNumber);
}
    },
    cancelTrainingNow : function (p1,p2,p3,p4,p5,p6,p7) {
        var t = Tabs.Train;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cityId = p2;
        params.requestType ="CANCEL_TRAINING";
        params.numtrptrn = p4;
        params.trnETA= p5;
        params.trnNeeded = p7;
        params.trnTmp = p6;
        params.typetrn= p3

        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelTraining.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                var t = Tabs.Train;
                if (rslt.ok) {
                    
                        var k=0;
                        var isPrestigeQueue = Seed.queue_unt["city"+p2][p1][7];
                        for(var j=0;j<Seed.queue_unt["city"+p2].length;j++){
                            if(j>p1 && (Seed.queue_unt["city" + p2][j][7] === isPrestigeQueue)){
                                Seed.queue_unt["city"+p2][j][2]=parseInt(rslt.dateTraining[k]["start"]);
                                Seed.queue_unt["city"+p2][j][3]=parseInt(rslt.dateTraining[k]["end"]);
                                k++;
                            }
                        }
                        Seed.queue_unt["city"+p2].splice(p1,1);
                        for(var i=1;i<5;i++){
                            var totalReturn=parseInt(unsafeWindow.unitcost["unt"+p3][i])*parseInt(p4)*3600/2;
                            Seed.resources["city"+p2]["rec"+i][0]=parseInt(Seed.resources["city"+p2]["rec"+i][0])+totalReturn;
                        }

                    t.dispTrainStatus ('<font color=#550000><B>'+culang.trainSuccessfullyDel+'</b></font><BR>');
                    t.displayCityStats();
                } else {
                    t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorCancelTrain+"</b></font><BR>");
                    t.displayCityStats();
                }
            },
            onFailure: function (rslt) {
                var t = Tabs.Train;
                t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorCancelTrain+"</b></font><BR>");
                t.displayCityStats();
            }
        });
    },
    cancelDefenseNow : function (typefrt, numtrpfrt, frtTmp, frtETA, frtNeeded, frtid, cityId, queueId){
        var t = Tabs.Train;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.pf =0;
        params.requestType = "CANCEL_FORTIFICATIONS";
        params.cityId = cityId;
        params.typefrt = typefrt;
        params.numtrpfrt =  numtrpfrt;
        params.frtETA = frtETA;
        params.frtTmp = frtTmp;
        params.frtNeeded = frtNeeded;
        params.frtid = frtid;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/cancelFortifications.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (message) {
                var rslt=eval("("+message.responseText+")");
                var t = Tabs.Train;
                if (rslt.ok) {
                    var k=0;
                    for(var j=0;j<Seed.queue_fort["city"+cityId].length;j++){
                        if(j>queueId){
                            Seed.queue_fort["city"+cityId][j][2]=parseInt(rslt.dateFortifications[k]["start"]);
                            Seed.queue_fort["city"+cityId][j][3]=parseInt(rslt.dateFortifications[k]["end"]);
                            k++;
                        }
                    }
                    unsafeWindow.update_seed(rslt.updateSeed);
                    Seed.queue_fort["city"+cityId].splice(queueId,1);
                    for(var i=1;i<5;i++){
                        var totalReturn=parseInt(unsafeWindow.fortcost["frt"+typefrt][i])*parseInt(numtrpfrt)*3600/2;
                        Seed.resources["city"+cityId]["rec"+i][0]=parseInt(Seed.resources["city"+cityId]["rec"+i][0])+totalReturn;
                    }
                    t.dispTrainStatus ('<font color=#550000><B>'+culang.trainSuccessfullyDelDefense+'</b></font><BR>');
                    t.displayCityStats();
                } else {

                    t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorCancel+"</b></font><BR>");
                    t.displayCityStats();
                }

            },
            onFailure: function () {
                var t = Tabs.Train;
                t.dispTrainStatus ("<font color=#550000><B>"+culang.mainError+": "+culang.trainErrorCancel+"</b></font><BR>");
                t.displayCityStats();
            },
        });
    },
    doQueue : function (cityId, tut, gam, que, errMsg){
        var t = Tabs.Train;
        try {
            t.displayCityStats();
            if (errMsg){
                t.dispTrainStatus ('<font color=#550000><B>'+culang.mainError+': '+ errMsg +'</b></font><BR>');
                t.setBusy(false);
                return;
            }
            var cmd = que.shift();
            if (!cmd){
                t.dispTrainStatus ('<B>'+culang.trainSuccessfully+'</b><BR>');
                t.setBusy(false);
                return;
            }
            if (cmd[0] == 'T'){
                t.dispTrainStatus ('<i> '+culang.trainStatus+' <span class="boldRed"> '+ cmd[2] +'</span> '+  unsafeWindow.unitcost['unt'+cmd[1]][0] +' '+culang.trainStatus2+' '+ Cities.byID[cityId].name +' '+culang.trainStatus3+' </i><BR>'); // ('+ que.length +' slot(s) restant(s)) - NEED TO FIX
                doTrain (cityId, tut, gam, cmd[1], cmd[2],
                    function(errMsg){
                        setTimeout(function (){Tabs.Train.doQueue(cityId, tut, gam, que, errMsg);}, (Math.random()*1000)+1000 );
                    }
                );
            }
        } catch (err) {
            t.dispTrainStatus ('<font color=#550000>'+culang.mainError+': '+ err.message +'</font><BR>');
            t.setBusy(false);
        }
    },
}
//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/Build.js">
/************************************************************************************
 *                        KOC POWER - TABS AUTO BUILD                                    *
 ************************************************************************************/
Tabs.build = { //TODO rename to Build
    tabOrder: TabOptions.toBuild,
    tabLabel: culang.tabLabelAutoBuild,
    myDiv: null,
    timer: null,
    buildTab: null,
    koc_buildslot: null,
    currentBuildMode: null,
    buildStates: [],
    loaded_bQ: [],
    lbQ: [],

    init: function(div){
        var t = Tabs.build;
        t.myDiv = div;
        t.koc_buildslot = unsafeWindow.buildslot;
        t.currentBuildMode = "build";
        t.buildStates = {
            running: false,
            help: false,
        };
        t.readBuildStates();

        for (var i = 0; i < Cities.cities.length; i++) {
            t["bQ_" + Cities.cities[i].id] = JSON2.parse(GM_getValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, '[]'));
            if (typeof t["bQ_" + Cities.cities[i].id] == 'undefined' || (t["bQ_" + Cities.cities[i].id]) == "") {
                t["bQ_" + Cities.cities[i].id] = [];
            }

        }

        var m = '<DIV id=pbBuildDivF class=pdxStat>'+culang.buildHead+'</div><TABLE id=pbbuildfunctions width=100% height=0% class=pdxTab><TR>';
        if (t.buildStates.running == false) {
            m += '<TD title="'+culang.buildButtonNote+'"><INPUT id=pbBuildRunning type=submit value="'+culang.buildButton+' = '+culang.buttonOFF+'"></td>';

        } else {
            m += '<TD><INPUT id=pbBuildRunning type=submit value="'+culang.buildButton+' = '+culang.buttonON+'"></td>';

        }
        m += '<TD><INPUT id=pbBuildMode type=submit value="'+culang.buildMode+' = '+culang.buttonOFF+'"></td>';


        m += '<TD>'+culang.buildModeSelect+' <SELECT id="pbBuildType">\
                <OPTION value=build>'+culang.buildModeLevel+'</option>\
                <OPTION value=max>'+culang.buildModeMax+'</option>\
                <OPTION value=destruct>'+culang.buildModeDestroy+'</option>\
                <OPTION value=destructnow>'+culang.buildModeDestroyNow+'</option>\
                </select></td>';
    
        m += '<TD style="text-align: right;">'+culang.buildAskForHelp+'&nbsp;';
        m += '<SELECT id="pbHelpRequest">\
                <OPTION value=off>' + culang.pbHelpRequestOff + '</option>\
                <OPTION value=chat>' + culang.pbHelpRequestChat + '</option>\
                <OPTION value=chatfb>' + culang.pbHelpRequestChatFB + '</option>\
                <OPTION value=chatfb10>' + culang.pbHelpRequestChatFB10 + '</option>\
                <OPTION value=chatfb20>' + culang.pbHelpRequestChatFB20 + '</option>\
                <OPTION value=chatfb30>' + culang.pbHelpRequestChatFB30 + '</option>\
                <OPTION value=chatfb60>' + culang.pbHelpRequestChatFB60 + '</option>\
                </select></td>'; //17.10.2012 Bommel
        m += '</tr></table></div>';
        m += '<DIV id=pbBuildDivQ class=pdxStat>'+culang.buildShowBuildQue+'</div><TABLE id=pbbuildqueues width=100% height=0% class=ptentry><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><B>' + Cities.cities[i].name + '</b></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><INPUT id=pbbuild_' + Cities.cities[i].id + ' type=submit value="'+culang.mainShow+'"></center></td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD colspan=2><CENTER><INPUT id=pbCancelAll_' + Cities.cities[i].id + ' type=submit value="'+culang.mainDeleteAll+'"></center></td>';
        }
        m += '</tr><TR>';

        for (var i = 0; i < Cities.cities.length; i++) {
            m += '<TD><div title="'+culang.buildShortBuildQuesNote+'">'+culang.buildShortBuildQues+'</div></td><TD id=pbbuildcount_' + Cities.cities[i].id + '>' + t["bQ_" + Cities.cities[i].id].length + '</td>';
        }
        m += '</tr><TR>';
        for (var i = 0; i < Cities.cities.length; i++) {
            t['totalTime_' + Cities.cities[i].id] = 0;
            cbQ = t["bQ_" + Cities.cities[i].id];
            if (typeof cbQ != 'undefined') {
                for (var j = 0; j < cbQ.length; j++) {
                    t['totalTime_' + Cities.cities[i].id] = parseInt(t['totalTime_' + Cities.cities[i].id]) + parseInt(cbQ[j].buildingTime);
                }
                timestring = timestr(t['totalTime_' + Cities.cities[i].id]);
            }
            m += '<TD><div title="'+culang.buildShortBuildTimeNote+'">'+culang.buildShortBuildTime+'</div></td><TD id=pbbuildtotal_' + Cities.cities[i].id + '>' + timestring + '</td>';
        }
        m += '</tr></table><SPAN class=boldRed id=pbbuildError></span>';
        t.myDiv.innerHTML = m;

        for (var i = 0; i < Cities.cities.length; i++) {
            var cityId = Cities.cities[i].id;
            var btnName = 'pbbuild_' + cityId;
            addQueueEventListener(cityId, btnName);
            var btn2Name = 'pbCancelAll_' + cityId;
            CancelAllEventListener(cityId, btn2Name);
            t.showBuildQueue(cityId, false);
        }

        setTimeout(function() { t.e_autoBuild(0);  }, 10000);

        ById('pbBuildType').addEventListener('change', function(){t.setBuildMode(this.value);}, false);
        ById('pbBuildRunning').addEventListener('click', function(){
            t.toggleBuildStateRunning(this);
        }, false);
        ById('pbBuildMode').addEventListener('click', function(){
            t.toggleStateMode(this);
        }, false);
        ById('pbHelpRequest').value = t.buildStates.help;
        ById('pbHelpRequest').addEventListener ('change', function (){
            t.buildStates.help = ById('pbHelpRequest').value;
            t.saveBuildStates();
        }, false);

        window.addEventListener('unload', t.onUnload, false);

        function addQueueEventListener(cityId, name){
            ById(name).addEventListener('click', function(){
                t.showBuildQueue(cityId, true);
            }, false);
        }

        function CancelAllEventListener(cityId, name){
            ById(name).addEventListener('click', function(){
                t["bQ_" + cityId] = [];
                t['totalTime_' + cityId] = 0;
                ById('pbbuildcount_' + cityId).innerHTML = 0;
                ById('pbbuildtotal_' + cityId).innerHTML = timestr(0);
            }, false);
        }


    },
    setBuildMode: function (type) {
        var t = Tabs.build;
        t.currentBuildMode = type;
    },
    e_autoBuild: function(cityIdT){
        var t = Tabs.build;
        var ilya=0;
        ById('pbbuildError').innerHTML = '';
        for (var i = 0; i < Cities.cities.length; i++) {
            var cityId = Cities.cities[i].id;
            ilya+=t["bQ_" + cityId].length;

        }
        if (ilya < 1) {

            t.toggleBuildStateRunning();
            return;
        }
        if (t.buildStates.running == true) {
            var now = unixTime();
            for (var i = 0; i < Cities.cities.length; i++) {
                var cityId = Cities.cities[i].id;
                var isBusy = false;
                /*if (cityIdT==cityId) {

                 isBusy=true
                 }*/

                var qcon = Seed.queue_con["city" + cityId];
                if (matTypeof(qcon)=='array' && qcon.length>0) {
                    if (parseIntNan(qcon[0][4]) > now)
                        isBusy = true;
                    else
                        qcon.shift();
                }
                if (isBusy) {
                    //TODO add info of remaining build time and queue infos
                    //actionLog(""+culang.tabLabelAutoBuild+"",Cities.cities[i].name+" : occupe.");
                    if (i >= Cities.cities.length-1) {
                        setTimeout(function() { t.e_autoBuild(cityId);  }, 15000); //should be at least 7.5 
                    }
                } else {
                    if (t["bQ_" + cityId].length > 0) { // something to do?
                        var bQi = t["bQ_" + cityId][0];   //take first queue item to build
                        //actionLog(""+culang.tabLabelAutoBuild+"",Cities.cities[i].name+" : Tentative de construction...");
                        t.doOne(bQi);
                        setTimeout(function() {

                            t.e_autoBuild(cityId);

                        },15000); //should be at least 10
                        break; // Am?liorations pour pas lancer tout en meme temps = risque de Captcha ou backOffWaitTime

                    } else {
                        //actionLog(""+culang.tabLabelAutoBuild+"",Cities.cities[i].name+" : rien. " + i + " >= " + Cities.cities.length);    
                        if (i >= Cities.cities.length-1) {
                            setTimeout(function() { t.e_autoBuild(cityId);  }, 15000); //should be at least 7.5 
                        }
                    }
                }

            }


        }

    },
    doOne : function (bQi){
        var t = Tabs.build;
        var currentcityid = parseInt(bQi.cityId);
        var cityName = t.getCityNameById(currentcityid);
        var time = parseInt(bQi.buildingTime);
        var mult = parseInt(bQi.buildingMult);
        var attempt = parseInt(bQi.buildingAttempt);
        var mode = bQi.buildingMode;
        var citpos = parseInt(bQi.buildingPos);
        if (Seed.buildings['city' + currentcityid]["pos" + citpos] != undefined && Seed.buildings['city' + currentcityid]["pos" + citpos][0] != undefined) {
            var l_bdgid = parseInt(bQi.buildingType);
            var bdgid = parseInt(Seed.buildings['city' + currentcityid]["pos" + citpos][0]);
            var l_curlvl = parseInt(bQi.buildingLevel);
            var curlvl = parseInt(Seed.buildings['city' + currentcityid]["pos" + citpos][1]);
            var l_bid = parseInt(bQi.buildingId);
            var bid = parseInt(Seed.buildings["city" + currentcityid]["pos" + citpos][3]);

            if (curlvl > 8 && mode == 'build') {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogLevel9OrHigher+"");
                return;
            };
            if (isNaN(curlvl)) {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogWrongLevel+"");
                return;
            }
            if (l_bdgid != bdgid) {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogBuildingType+"");
                return;
            }
            if (l_bid != bid) {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogBuildingID+"");
                return;
            }
            if (l_curlvl < curlvl) {
                t.cancelQueueElement(0, currentcityid, time, false);
                actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogBuildingEqualHigher+"");
                return;
            }
            if (l_curlvl > curlvl && mode == 'build') {
                t.requeueQueueElement(bQi);
                return;
            }

            if (mode == 'destruct') {
                var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                params.cid = currentcityid;
                params.bid = "";
                params.pos = citpos;
                params.lv = curlvl - 1;
                if (curlvl >= 1) {
                    params.bid = bid;
                }
                params.type = bdgid;
                new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/destruct.php" + unsafeWindow.g_ajaxsuffix, {
                    method: "post",
                    parameters: params,
                    onSuccess: function(rslt){
                        if (rslt.ok) {
                            actionLog(""+culang.tabLabelAutoBuild+"",cityName + ": "+culang.buildLogDestructRessource+"");
                            Seed.queue_con["city" + currentcityid].push([bdgid, 0, parseInt(rslt.buildingId), unsafeWindow.unixtime(), unsafeWindow.unixtime() + time, 0, time, citpos]);
                            if (params.cid == uW.currentcityid) {
                                uW.update_bdg();
                                uW.queue_changetab_building();
                            }
                            t.cancelQueueElement(0, currentcityid, time, false);
                        } else {
                            var errmsg = unsafeWindow.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);
                            actionLog(""+culang.tabLabelAutoBuild+"",cityName + ": " + errmsg);
                            t.requeueQueueElement(bQi);
                            ById('pbbuildError').innerHTML = errmsg;

                        }
                    },
                    onFailure: function(){
                        ById('pbbuildError').innerHTML = ""+culang.buildLogDestructError+"";
                    }
                })
            }
            if (mode == 'build') {
                var invalid = false;
                var chk = unsafeWindow.checkreq("bdg", bdgid, curlvl);
                for (var c = 0; c < chk[3].length; c++) {
                    if (chk[3][c] == 0) {
                        invalid = true;
                    }
                }
                if (invalid == false) {
                    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                    params.cid = currentcityid;
                    params.bid = "";
                    params.pos = citpos;
                    params.lv = curlvl + 1;
                    if (params.lv > 9){
                        t.cancelQueueElement(0, currentcityid, time, false);
                        actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildLogBuildingLevelTen+"");
                        return;
                    }
                    if (params.lv > 1) {
                        params.bid = bid;
                    }
                    params.type = bdgid;


                    // NOUVEAU ! Test si vous avez assez de matos ^^^
                    if ((Seed.resources["city" + currentcityid].rec1[0] >= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][1]) * mult * 3600) &&
                        (Seed.resources["city" + currentcityid].rec2[0] >= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][2]) * mult * 3600) &&
                        (Seed.resources["city" + currentcityid].rec3[0] >= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][3]) * mult * 3600) &&
                        (Seed.resources["city" + currentcityid].rec4[0] >= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][4]) * mult * 3600) &&
                        (Seed.citystats["city" + currentcityid].gold[0] >= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][5]) * mult)) {



                        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/construct.php" + unsafeWindow.g_ajaxsuffix, {
                            method: "post",
                            parameters: params,
                            onSuccess: function(rslt){
                                if (rslt.ok) {
                                    // actionLog(""+culang.tabLabelAutoBuild+"",cityName + " : Construction Reussi !"); 
                                    Seed.resources["city" + currentcityid].rec1[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][1]) * mult * 3600;
                                    Seed.resources["city" + currentcityid].rec2[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][2]) * mult * 3600;
                                    Seed.resources["city" + currentcityid].rec3[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][3]) * mult * 3600;
                                    Seed.resources["city" + currentcityid].rec4[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][4]) * mult * 3600;
                                    Seed.citystats["city" + currentcityid].gold[0] -= parseInt(unsafeWindow.buildingcost["bdg" + bdgid][5]) * mult;
                                    Seed.queue_con["city" + currentcityid].push([bdgid, curlvl + 1, parseInt(rslt.buildingId), unsafeWindow.unixtime(),  unsafeWindow.unixtime() + time, 0, time, citpos]);
                                    if (params.cid == uW.currentcityid) {
                                        uW.update_bdg();
                                        uW.queue_changetab_building();
                                    }
                                    if (ById('pbHelpRequest').value != 'off')
                                        t.bot_gethelp(params.bid, currentcityid, time);
                                    t.cancelQueueElement(0, currentcityid, time, false);
                                } else {
                                    if (rslt.user_action) {
                                        if (rslt.user_action!="backOffWaitTime") {
                                            actionLog(""+culang.tabLabelAutoBuild+"","<b><font color=red>Detection Captcha  !!!</font></b>");
                                            new CdialogCancelContinue('<SPAN class=boldRed>CAPTCHA ALERT ! Trop de construction !</span>', null, null, mainPop.getMainDiv);
                                        }

                                    } else {
                                        var errmsg = unsafeWindow.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);
                                        if (rslt.error_code == 103) {
                                            t.cancelQueueElement(0, currentcityid, time, false);
                                            actionLog(""+culang.tabLabelAutoBuild+"", Cities.byID[currentcityid].name +": "+culang.buildLogBuildingProcess2+"");
                                        } else {
                                            t.requeueQueueElement(bQi);
                                            actionLog(""+culang.tabLabelAutoBuild+"", Cities.byID[currentcityid].name +' : '+ errmsg);
                                            ById('pbbuildError').innerHTML = Cities.byID[currentcityid].name +': '+ errmsg + " "+culang.buildLogBuildingProcessAgain+"";
                                        }
                                    }

                                }
                            },
                            onFailure: function(){
                                ById('pbbuildError').innerHTML = ""+culang.buildConnectError+"";
                            }
                        });

                    } else {
                        t.requeueQueueElement(bQi);
                        actionLog(""+culang.tabLabelAutoBuild+"", Cities.byID[currentcityid].name +' : <font color=red>'+culang.buildLogNoRessource+'</font>');
                    }


                } else {
                    t.requeueQueueElement(bQi);
                    //actionLog(""+culang.tabLabelAutoBuild+"", Cities.byID[currentcityid].name +' : <font color=red>Bizarreee !!</font>'); 
                    t.countbizarre++;
                    if (t.countbizarre>10) {
                        actionLog(""+culang.tabLabelAutoBuild+"",""+culang.buildBuildTenFaild+"");
                        reloadKOC();

                    }
                }
            }
        } else {
            t.cancelQueueElement(0, currentcityid, time, false);
            //actionLog(""+culang.tabLabelAutoBuild+"","Queue item deleted: Building does not exist!!!");
        }
    },
    countbizarre:0,
    requeueQueueElement: function (bQi) {
        var t = Tabs.build;
        var cityId = bQi.cityId;
        var buildingPos = parseInt(bQi.buildingPos);
        var buildingId = parseInt(bQi.buildingId);
        var buildingLevel = parseInt(bQi.buildingLevel);
        var buildingType = parseInt(bQi.buildingType);
        var buildingTime = parseInt(bQi.buildingTime);
        var buildingMult = parseInt(bQi.buildingMult);
        var buildingAttempts = parseInt(bQi.buildingAttempts);
        var buildingMode = bQi.buildingMode;

        t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts + 1, buildingMult, buildingMode);
        t.cancelQueueElement(0, cityId, buildingTime, false);
    },
    show: function(){
        var t = Tabs.build;
    },
    bot_buildslot: function(c, a){
        var t = Tabs.build;
        var cityId = t.getCurrentCityId();
        var buildingPos   = c.id.split("_")[1];
        var buildingType  = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][0]);
        var buildingLevel = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][1]);
        var buildingId    = parseInt(Seed.buildings['city' + cityId]["pos" + buildingPos][3]);
        var buildingAttempts = 0;
        var loaded_bQ = t["bQ_" + cityId];
        if (typeof Seed.queue_con['city' + cityId][0] != 'undefined') {
            var current_construction_pos = Seed.queue_con['city' + cityId][0][2];
        } else {
            var current_construction_pos = "";
        }
        if (loaded_bQ.length == 0 && current_construction_pos != "" ) {
            if (current_construction_pos != 'NaN' && current_construction_pos == buildingId) {
                buildingLevel += 1;
            }
        } else {
            if (current_construction_pos != "" && current_construction_pos == buildingId) {
                buildingLevel += 1;
            }
            for (var i = 0; i < loaded_bQ.length; i++) {
                var loadedCity = loaded_bQ[i].cityId;
                var loadedSlot = loaded_bQ[i].buildingPos;
                if (loadedSlot == buildingPos && loadedCity == cityId) {
                    buildingLevel += 1;
                }
                if (loaded_bQ[i].buildingMode == 'destruct' && loadedSlot == buildingPos && loadedCity == cityId) {
                    t.modalmessage(''+culang.buildDestrucAlreadyInQueue+'');
                    return;
                }
            }
        }
        if (t.currentBuildMode == "build") {
            if (buildingLevel >= 9) {
                t.modalmessage(''+culang.buildBuildTryedLevelTen+'');
                return;
            }
            var buildingMode = "build";
            var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
            var buildingMult = result[0];
            var buildingTime = result[1];
            var queueId = loaded_bQ.length;
            t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
            t._addTab(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode);
        }
        if (t.currentBuildMode == "max") {
            var buildingMode = "build";
            for (var bL = buildingLevel; bL <9; bL++) {
                var queueId = loaded_bQ.length;
                var result = t.calculateQueueValues(cityId, bL, buildingType, buildingMode);
                var buildingMult = result[0];
                var buildingTime = result[1];
                queueId = queueId ;
                t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, bL, buildingAttempts, buildingMult, buildingMode);
                t._addTab(queueId, cityId, buildingType, buildingTime, bL, buildingAttempts, buildingMode);
            }
        }
        if (t.currentBuildMode == "destruct") {
            var buildingMode = "destruct";
            var result = t.calculateQueueValues(cityId, buildingLevel, buildingType, buildingMode);
            var buildingMult = result[0];
            var buildingTime = result[1];
            var queueId = loaded_bQ.length;
            t.addQueueItem(cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode);
            t._addTab(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode);
        }
        if (t.currentBuildMode == "destructnow") {

            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.cityId = cityId;
            params.buildingId = buildingId;
            params.pos = buildingPos;
            params.requestType = "DESTROY_BUILDING_DRAGON_STOMP_MEDAL";
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/destroyBuilding.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function(rslt){
                    if (rslt.ok) {
                        uW.seed.items.i9=Number(uW.seed.items.i9)-1;
                        uW.ksoItems[9].subtract();

                        delete Seed.buildings["city"+cityId]["pos"+buildingPos];

                        uW.citysel_click(ById("citysel_"+(Cities.byID[cityId].idx+1)));

                    } else {
                        var errmsg = unsafeWindow.printLocalError(rslt.error_code || null, rslt.msg || null, rslt.feedback || null);

                        ById('pbbuildError').innerHTML = errmsg;

                    }
                },
                onFailure: function(){
                    ById('pbbuildError').innerHTML = "Error for Destruction!";
                }
            })


        }

    },
    calculateQueueValues: function (cityId, buildingLevel, buildingType, buildingMode) {
        var t = Tabs.build;
        var now = unixTime();
        if (buildingMode == 'build') {
            var buildingMult = Math.pow(2, buildingLevel);
        }
        if (buildingMode == 'destruct') {
            var buildingMult = Math.pow(2, buildingLevel - 2);
        }

        var knights = Seed.knights["city" + cityId];
        if (knights) {
            var polKniId = parseInt(Seed.leaders['city' + cityId].politicsKnightId);
            if (polKniId) {
                var polValue = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politics);
                var polBoost = parseInt(Seed.knights['city' + cityId]['knt' + polKniId].politicsBoostExpireUnixtime);
                if ((polBoost - now) > 0) {
                    polValue = parseInt(polValue * 1.25);
                }
            } else {
                polValue = 0;
            }
        } else {
            polValue = 0;
        }

        var buildingTime = unsafeWindow.buildingcost["bdg" + buildingType][7] * buildingMult;



        if (parseInt(buildingType) < 6 && parseInt(buildingType) > 0 && buildingMult == 1) {
            buildingTime = 15;
        }
        var C=uW.cm.ThroneController.effectBonus(78);

        if (buildingMode == 'build') {
            buildingTime = parseInt(buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16)));

        }
        if (buildingMode == 'destruct') {
            buildingTime = parseInt(buildingTime / (1 + 0.005 * polValue + 0.1 * parseInt(Seed.tech.tch16)));
            if (buildingTime % 1 > 0) {
                buildingTime = parseInt(buildingTime);
            }
        }
        buildingTime=Math.round(buildingTime/(1+(C/100)));
        var result = new Array(buildingMult, buildingTime);
        return result;
    },

    bot_gethelp: function (f, currentcityid, time) {
        var t = Tabs.build;
    
        //Chat Anfrage
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.bid = f;
        params.ctrl = 'AskForHelp';
        params.action = 'getHelpData';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                unsafeWindow.handleHelpCallback (rslt.data);
            },
            onFailure: function (rslt) {
                t.bot_gethelp (f, currentcityid, time);
                return;
            },
        });
        
        //FB Anfrage
        var help = ById('pbHelpRequest').value;
        if (help == 'off' || help == 'chat') return;
        if (help == 'chatfb10' && time < 600) return;
        if (help == 'chatfb20' && time < 1200) return;
        if (help == 'chatfb30' && time < 1800) return;
        if (help == 'chatfb60' && time < 3600) return;
        var a = Seed.queue_con["city" + currentcityid];
        var e = 0;
        var d = 0;
        for (var c = 0; c < a.length; c++) {
            if (parseInt(a[c][2]) == parseInt(f)) {
                e = parseInt(a[c][0]);
                d = parseInt(a[c][1]);
                break;
            }
        }
        var b = new Array();
        b.push(["REPLACE_CiTyId", currentcityid]);
        b.push(["REPLACE_LeVeLbUiLdInG", d]);
        b.push(["REPLACE_BuIlDiNgNaMe", unsafeWindow.buildingcost["bdg" + e][0]]);
        b.push(["REPLACE_LeVeLiD", d]);
        b.push(["REPLACE_AsSeTiD", f]);
        var g = function(h, i) {
            unsafeWindow.continuation_95(h, i);
            if (!h) {
                var j = d > 1 ? unsafeWindow.cm.SpeedUpType.upgrade : unsafeWindow.cm.SpeedUpType.build;
                unsafeWindow.cm.ClientSideCookieManager.setCookie(j, false)
            }
        };
        unsafeWindow.common_postToProfile("95", unsafeWindow.Object.cloneFeed(unsafeWindow.template_data_95), unsafeWindow.Object.cloneFeed(unsafeWindow.actionlink_data_95), g, b)
    },
    addQueueItem: function (cityId, buildingPos, buildingType, buildingId, buildingTime, buildingLevel, buildingAttempts, buildingMult, buildingMode) {
        var t = Tabs.build;
        var lbQ = t["bQ_" + cityId];
        lbQ.push({
            cityId:             cityId,
            buildingPos:        buildingPos,
            buildingType:         buildingType,
            buildingId:         buildingId,
            buildingTime:         buildingTime,
            buildingLevel:         buildingLevel,
            buildingAttempts:     buildingAttempts,
            buildingMult:         buildingMult,
            buildingMode:         buildingMode
        });
        t.modifyTotalTime(cityId, 'increase', buildingTime);
    },
    modalmessage: function(message){
        var t = Tabs.build;
        var timeout = 10000;
        var content = ""+culang.buildAutoCloseIn10Seconds+"<br>"
        content += message;
        unsafeWindow.Modal.showAlert(content);
        setTimeout(function() {
            unsafeWindow.Modal.hideModal();
        }, timeout);
    },
    modifyTotalTime: function (cityId, type, buildingTime) {
        var t = Tabs.build;
        var element = ById('pbbuildcount_' + cityId);
        var currentCount = parseInt(element.innerHTML);
        if (type == "increase") {
            t['totalTime_' + cityId] = t['totalTime_' + cityId] + buildingTime;
            var currentCount = currentCount + 1;
        }
        if (type == "decrease") {
            t['totalTime_' + cityId] = t['totalTime_' + cityId] - buildingTime;
            var currentCount = currentCount - 1;
        }
        element.innerHTML = currentCount;
        ById('pbbuildtotal_' + cityId).innerHTML = timestr(t['totalTime_' + cityId]);
    },
    hide: function(){
        var t = Tabs.build;
    },
    onUnload: function(){
        var t = Tabs.build;
        for (var i = 0; i < Cities.cities.length; i++) {
            t["bQ_" + Cities.cities[i].id].sort(function(a,b){return a.buildingTime - b.buildingTime});
            if (!ResetAll) GM_setValue('bQ_' + getServerId() + '_' + Cities.cities[i].id, JSON2.stringify((t["bQ_" + Cities.cities[i].id])));
        }
        t.saveBuildStates();
    },
    _addTab: function(queueId, cityId, buildingType, buildingTime, buildingLevel, buildingAttempts, buildingMode){
        var t = Tabs.build;
        var row = ById('pbCityQueueContent').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = queueId;
        if (buildingMode == "destruct") {
            row.insertCell(1).innerHTML = '<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/bonus_att.png">';
        }
        else {
            row.insertCell(1).innerHTML = '<img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/bonus_prod.png">';
        }
        row.insertCell(2).innerHTML = unsafeWindow.buildingcost['bdg' + buildingType][0];
        row.insertCell(3).innerHTML = timestr(buildingTime);
        if (buildingMode == "destruct") {
            row.insertCell(4).innerHTML = 0;
        } else {
            row.insertCell(4).innerHTML = buildingLevel + 1;
        }
        row.insertCell(5).innerHTML = buildingAttempts;
        row.insertCell(6).innerHTML = '<a id="queuecancel_' + queueId + '"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></span></a>';
        ById('queuecancel_' + queueId).addEventListener('click', function(){
            t.cancelQueueElement(queueId, cityId, buildingTime, true);
        }, false);
    },
    cancelQueueElement: function(queueId, cityId, buildingTime, showQueue){
        var t = Tabs.build;
        var queueId = parseInt(queueId);
        t["bQ_" + cityId].splice(queueId, 1);
        t.modifyTotalTime(cityId, 'decrease', buildingTime);

        if (showQueue == true) {
            t.showBuildQueue(cityId, false);
        }
    },
    showBuildQueue: function(cityId, focus){
        var t = Tabs.build;
        clearTimeout (t.timer);
        var popBuildQueue = null;
        var cityName = t.getCityNameById(cityId);
        if (t.popBuildQueue == null) {
            t.popBuildQueue = new CPopup('pbbuild_' + cityId, 0, 0, 350, 500, true, function() {clearTimeout (t.timer);});
        }
        var m = '<DIV style="max-height:460px; overflow-y:auto"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbTabPad" id="pbCityQueueContent">';
        t.popBuildQueue.getMainDiv().innerHTML = '</table></div>' + m;
        t.popBuildQueue.getTopDiv().innerHTML = '<div class="popupBanner">' + cityName + ': <INPUT id=pbOptimizeByTime type=submit value="'+culang.buildBuildQueueSort+'"></div>';
        t.popBuildQueue.centerMe (mainPop.getMainDiv());

        t.paintBuildQueue(cityId);
        if (focus)
            t.popBuildQueue.show(true);
        ById('pbOptimizeByTime').addEventListener('click', function(){t.clearBuildQueue();t.paintBuildQueue(cityId, true);}, false);
        t.timer = setTimeout (function() {t.showBuildQueue(cityId, false)}, 45000);
    },
    paintBuildQueue: function(cityId, optimize){
        var t = Tabs.build;
        var lbQ = t["bQ_" + cityId];
        if (optimize == true) {
            lbQ.sort(function(a,b){return a.buildingTime - b.buildingTime});
        }
        t["bQ_" + cityId] = lbQ;
        for (var i = 0; i < lbQ.length; i++) {
            var queueId = i;
            t._addTab(queueId, lbQ[i].cityId, lbQ[i].buildingType, lbQ[i].buildingTime, lbQ[i].buildingLevel, lbQ[i].buildingAttempts, lbQ[i].buildingMode);
        }
    },
    clearBuildQueue: function() {
        var t = Tabs.build;
        var table = ById('pbCityQueueContent');
        var rows = table.rows;
        while(rows.length)
            table.deleteRow(rows.length-1);
    },
    getCurrentCityId: function(){
        if (!unsafeWindow.currentcityid)
            return null;
        return unsafeWindow.currentcityid;
    },
    saveBuildStates: function(){
        var t = Tabs.build;
        var serverID = getServerId();
        GM_setValue('buildStates_' + serverID, JSON2.stringify(t.buildStates));
    },
    readBuildStates: function(){
        var t = Tabs.build;
        var serverID = getServerId();
        s = GM_getValue('buildStates_' + serverID);
        if (s != null) {
            states = JSON2.parse(s);
            for (k in states)
                t.buildStates[k] = states[k];
        }
    },
    toggleBuildStateRunning: function(obj){
        var t = Tabs.build;
        obj = ById('pbBuildRunning');
        if (t.buildStates.running == true) {
            t.buildStates.running = false;
            t.saveBuildStates();
            if (obj) obj.value = culang.buildButton+" = "+culang.buttonOFF;
        }
        else {
            t.buildStates.running = true;
            t.saveBuildStates();
            if (obj) obj.value = culang.buildButton+" = "+culang.buttonON;
            t.e_autoBuild(0);
        }
    },
    toggleStateMode: function(obj){
        var t = Tabs.build;
        obj = ById('pbBuildMode');
        if (obj.value == culang.buildMode+' = '+culang.buttonOFF) {
            unsafeWindow.buildslot = t.bot_buildslot;
            obj.value = culang.buildMode+' = '+culang.buttonON;

        } else {
            unsafeWindow.buildslot = t.koc_buildslot;
            obj.value = culang.buildMode+' = '+culang.buttonOFF;
        }
    },
    getCityNameById: function (cityId) {
        return Cities.byID[cityId].name;
    },
}
//</editor-fold>

//<editor-fold desc="SPLIT:Tabs/AutoCraft.js">
/************************************************************************************
 *                        KOC POWER - TABS AUTO CRAFT                                    *
 ************************************************************************************/
Tabs.AutoCraft = {
    tabOrder: TabOptions.toAutoCraft,
    tabLabel: culang.tabLabelAutoCraft,
    myDiv: null,
    timer: null,
    crafting: [],
    craftinfo : {},
    craftitems : {},
    myDiv: null,
    timer: null,
    timerStat: null,
    numcity :-1,
    wait:false,
    viewstats: null,
    options: {
        running: false,
        CraftingNb: {},
        CraftingNbC: {},
        throneCheck: false,
        throneSet: 1,
        SimpleItems: false,
        stats: {},
    },
    id: {},
    
    readOptions: function() {
        var t = Tabs.AutoCraft;
        var a = getServerId();
        var u = getMyUserId();
        var s = GM_getValue("CraftingData_"+a+"_"+u);
        if(s != null){
            opts = JSON2.parse(s);
            for(k in opts){
                t.options[k] = opts[k];
            }
        }
    },
    saveOptions: function() {
        var t = Tabs.AutoCraft;
        var a = getServerId();
        var u = getMyUserId();
        setTimeout(function(){
            GM_setValue("CraftingData_"+a+"_"+u, JSON2.stringify(t.options));
        },0)
    },

    init: function(div){
        var t = Tabs.AutoCraft;
        t.myDiv = div;
        t.readOptions();
        var m = '<DIV id=pbBuildDivF class=pdxStat>'+culang.craftHead+'</div><TABLE width=100% height=0% class=pdxTab><TR>';
        if (t.options.running == false) {
            m += '<TD style="text-align: center;"><INPUT id=pbCraftRunning type=submit value="'+culang.craftButton+' = '+culang.buttonOFF+'"></td>';
        } else {
            m += '<TD style="text-align: center;"><INPUT id=pbCraftRunning type=submit value="'+culang.craftButton+' = '+culang.buttonON+'"></td>';
            t.timer=setInterval(t.Start,8000);
        }
        m += "<td style='text-align: center;'><input id=pbCraftStats type=submit value='"+culang.craftStats+"'></td>";
        m += "<td><input type=checkbox id=pbCraftThroneCheck "+ (t.options.throneCheck?'CHECKED':'') +"> " + culang.mainCraftOnlyThroneSet;
        m += " <SELECT id=pbCraftThroneSet>"; 
        for (i=1;i<=Seed.throne.slotNum;i++){
            m += '<option value="'+i+'">'+i+'</option>';
        }
        m +='</select><br>';
        m += "<input type=checkbox id=pbCraftSimpleItems "+ (t.options.SimpleItems?'CHECKED':'') +"> " + culang.mainCraftSimpleItems;
        m +='</td>';
        m +='<td id="pbCraftSpeed" style="text-align:center;"></td>';
        m += '</tr></table>';
        m += '<DIV id=pbBuildDivQ class=pdxStat>'+culang.craftHeadStats+'</div><span id="KsCraftStat"></span>';
        m += '<DIV id=pbBuildDivQ class=pdxStat>'+culang.craftHeadSettings+'</div><div style="max-height:700px;overflow-y:auto"><TABLE width=100% height=0% class=pdxTab style="border-collapse:collapse;"><TR>';

        m += "<td colspan=2><b><u>"+culang.mainItems+"</u></b></td>";
        m += "<td style='text-align:center;'><b><u>"+culang.mainInventory+"</u></b></td>";
        m += "<td style='text-align:center;'><b><u>"+uW.g_js_strings.commonstr.cities+"</u></b></td>";
        m += "<td><b><u>"+culang.mainAmount+"</u></b></td>";
        m += "<td width=10 style='border-right: 1px solid black;'>&nbsp;</td><td width=10>&nbsp;</td>";
        m += "<td colspan=2><b><u>"+culang.mainItems+"</u></b></td>";
        m += "<td style='text-align:center;'><b><u>"+culang.mainInventory+"</u></b></td>";
        m += "<td style='text-align:center;'><b><u>"+uW.g_js_strings.commonstr.cities+"</u></b></td>";
        m += "<td><b><u>"+culang.mainAmount+"</u></b></td></tr>";
        m += "<tr>";

        var z=0;
        for(var i=0; i < uW.recipelist[1].length; i++){
            var h = parseInt(uW.recipelist[1][i].output_item_id);
            t.craftitems[uW.recipelist[1][i].recipe_id] = h;
            t.craftinfo[h] = {};
            t.craftinfo[h].recipe_id = uW.recipelist[1][i].recipe_id;
            t.craftinfo[h].category = uW.recipelist[1][i].category;
            t.craftinfo[h].input = uW.recipelist[1][i].input;
            t.craftinfo[h].requirements = uW.recipelist[1][i].requirements;
            t.craftinfo[h].consolation = uW.recipelist[1][i].consolation_item_id;
            var title = addCommas(t.craftinfo[h].input.resources['1']) + " " + uW.g_js_strings.commonstr.aetherstones + "\n";
            if (t.craftinfo[h].input.items.length == undefined) {
                for (j in t.craftinfo[h].input.items) {
                    var anz = parseInt(t.craftinfo[h].input.items[j]);            
                    title += anz + " " + uW.itemlist["i"+j].name + "\n";
                }
            }
            title += uW.buildingcost.bdg20[0] + ' Level ' + t.craftinfo[h].requirements.building;
            m += "<td width='27'><img title='"+title+"' src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td>";
            m += "<td>"+uW.itemlist["i"+h].name+"</td>";
            m += "<td id='KsCraft_nbi_"+h+"' style='text-align:center;font-weight:bold;'>"+parseIntNan(Seed.items["i"+h])+"</td>";
            if (!t.options.stats[h]) t.options.stats[h] = {'e':0,'f':0,'s':0}; //Error, Fail, Success
            if (!t.options.CraftingNbC[h]) t.options.CraftingNbC[h] = {0:"y", 1:"y", 2:"y", 3:"y", 4:"y", 5:"y", 6:"y", 7:"y"};
            m += "<td>";
            for(j=0; j<Cities.numCities; j++) {
                if (t.options.CraftingNbC[h][j] == "y") {
                    m += "<input type=submit id='KsCraft_nbc_"+j+"_"+h+"' style='width:14px;height:14px; margin:1px;text-align:center; background-color: green; color:white; font-size:9px;font-family:arial;font-weight:bold;border-radius:0;' value='"+(j+1)+"'>";
                } else {
                    m += "<input type=submit id='KsCraft_nbc_"+j+"_"+h+"' style='width:14px;height:14px; margin:1px;text-align:center; background-color: red; color:white; font-size:9px;font-family:arial;font-weight:bold;border-radius:0;' value='"+(j+1)+"'>";
                }
            }
            m += "</td>";
            m += "<td><input style='text-align:center;' type=text size=4 id='KsCraft_nb_"+h+"' value='"+ parseIntNan(t.options.CraftingNb[h]) +"'></td>";
            if ((z+1)%2 == 1) m += "<td style='border-right:1px solid black;'></td><td></td>";
            if ((z+1)%2 == 0) m += "</tr><tr>";
            z++;
        }
        for(var i=0; i < uW.recipelist[3].length; i++){
            var h = parseInt(uW.recipelist[3][i].output_item_id);
            t.craftitems[uW.recipelist[3][i].recipe_id] = h;
            t.craftinfo[h] = {};
            t.craftinfo[h].recipe_id = uW.recipelist[3][i].recipe_id;
            t.craftinfo[h].category = uW.recipelist[3][i].category;
            t.craftinfo[h].input = uW.recipelist[3][i].input;
            t.craftinfo[h].requirements = uW.recipelist[3][i].requirements;
            t.craftinfo[h].consolation = uW.recipelist[1][i].consolation_item_id;
            var title = addCommas(t.craftinfo[h].input.resources['1']) + " " + uW.g_js_strings.commonstr.aetherstones + "\n";
            if (t.craftinfo[h].input.items.length == undefined) {
                for (j in t.craftinfo[h].input.items) {
                    var anz = parseInt(t.craftinfo[h].input.items[j]);            
                    title += anz + " " + uW.itemlist["i"+j].name + "\n";
                }
            }
            title += uW.buildingcost.bdg20[0] + ' Level ' + t.craftinfo[h].requirements.building;
            m += "<td width='27'><img title='"+title+"' src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td>";
            m += "<td>"+uW.itemlist["i"+h].name+"</center></td>";
            m += "<td id='KsCraft_nbi_"+h+"'  style='text-align:center;font-weight:bold;'>"+parseIntNan(Seed.items["i"+h])+"</td>";
            if (!t.options.stats[h]) t.options.stats[h] = {'e':0,'f':0,'s':0}; //Error, Fail, Success
            if (!t.options.CraftingNbC[h]) t.options.CraftingNbC[h] = {0:"y", 1:"y", 2:"y", 3:"y", 4:"y", 5:"y", 6:"y", 7:"y"};
            m += "<td>";
            for(j=0; j<Cities.numCities; j++) {
                if (t.options.CraftingNbC[h][j] == "y") {
                    m += "<input type=submit id='KsCraft_nbc_"+j+"_"+h+"' style='width:14px;height:14px; margin:1px;text-align:center; background-color: green; color:white; font-size:9px;font-family:arial;font-weight:bold;border-radius:0;' value='"+(j+1)+"'>";
                } else {
                    m += "<input type=submit id='KsCraft_nbc_"+j+"_"+h+"' style='width:14px;height:14px; margin:1px;text-align:center; background-color: red; color:white; font-size:9px;font-family:arial;font-weight:bold;border-radius:0;' value='"+(j+1)+"'>";
                }
            }
            m += "</td>";
            m += "<td><input style='text-align:center;' type=text size=4 id='KsCraft_nb_"+h+"' value='"+ parseIntNan(t.options.CraftingNb[h]) +"'></td>";
            if ((z+1)%2 == 1) m += "<td style='border-right:1px solid black;'></td><td></td>";
            if ((z+1)%2 == 0) m += "</tr><tr>";
            z++;
        }
        m+="</tr></table></div>";
        t.myDiv.innerHTML = m;
        
        t.id["pbCraftStats"] = ById("pbCraftStats");
        t.id["pbCraftStats"].addEventListener ('click', function (){t.viewCraftStats()}, false);
        t.id["KsCraftStat"] = ById("KsCraftStat");
        t.id["pbCraftThroneCheck"] = ById("pbCraftThroneCheck");
        t.id["pbCraftThroneCheck"].addEventListener ('click', function(e){
            t.options.throneCheck = e.target.checked;
            t.saveOptions();
        }, false);        
        t.id["pbCraftThroneSet"] = ById("pbCraftThroneSet");
        t.id["pbCraftThroneSet"].value = t.options.throneSet;
        t.id["pbCraftThroneSet"].addEventListener ('change',function(e){
            t.options.throneSet = this.value;
            t.saveOptions();
        }, false);        
        t.id["pbCraftSimpleItems"] = ById("pbCraftSimpleItems");
        t.id["pbCraftSimpleItems"].addEventListener ('click', function(e){
            t.options.SimpleItems = e.target.checked;
            t.saveOptions();
        }, false);    
        t.id["pbCraftSpeed"] = ById("pbCraftSpeed");
        t.id["pbCraftRunning"] = ById("pbCraftRunning");
        t.id["pbCraftRunning"].addEventListener ('click', function (){t.toggleCraftStateRunning()}, false);
        for(var h in t.craftinfo) {
            t.id["KsCraft_nbi_"+h] = ById("KsCraft_nbi_"+h);
            t.id["KsCraft_nb_" +h] = ById("KsCraft_nb_" +h);
            t.id["KsCraft_nb_" +h].addEventListener ('keyup', function () {
                var item = ById(this.id);
                item.value = parseIntNan(item.value);
                t.saveCraftState();
            }, false);
            for(j=0; j<Cities.numCities; j++) {
                t.id["KsCraft_nbc_"+j+"_"+h] = ById("KsCraft_nbc_"+j+"_"+h);
                t.id["KsCraft_nbc_"+j+"_"+h].addEventListener ('click', function (){
                    var item = ById(this.id);
                    var info = this.id.split("_");
                    var h = info[3];
                    var j = info[2];
                    if (!t.options.CraftingNbC[h][j]) t.options.CraftingNbC[h][j] = "y";
                    if (t.options.CraftingNbC[h][j] == "y") {
                        t.options.CraftingNbC[h][j] = "n";
                        item.style.backgroundColor = "red";
                    } else {
                        t.options.CraftingNbC[h][j] = "y";
                        item.style.backgroundColor = "green";
                    }
                    t.saveCraftState();
                }, false);
            }
        }
        t.updateStat();
    },
    
    viewCraftStats: function() {
        var t = Tabs.AutoCraft;
        if(t.viewstats == null)
            t.viewstats = new CPopup ('pbviewcraftstats', 0, 0, 900, 750, true);
        t.viewstats.centerMe (mainPop.getMainDiv());
        var m= '<TABLE width=100% class=pdxTab style="border-collapse:collapse;">';
        m += "<tr>";
        m += "<td colspan=2><b><u>"+culang.mainItems+"</b></u></td>";
        m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsSuccess+"</b></u></td>";
        m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsFail+"</b></u></td>";
        m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsSuccessrate+"</b></u></td>";
        m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsError+"</b></u></td>";
        m += "<td style='border-right:1px solid black; width:10px;'>&nbsp;</td><td style='width:10px;'>&nbsp;</td>";
        m += "<td colspan=2><b><u>"+culang.mainItems+"</b></u></td>";
        m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsSuccess+"</b></u></td>";
        m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsFail+"</b></u></td>";
        m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsSuccessrate+"</b></u></td>";
        m += "<td style='padding: 0 3px 0 3px;'><b><u>"+culang.craftStatsError+"</b></u></td>";
        m += "</tr>";
        var z=0;
        for(var h in t.craftinfo) {
            z++;
            if (z%2 == 1) m += "<tr>";
            m += "<td width='27'><img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg' width=25></td>";
            m += "<td>"+uW.itemlist["i"+h].name+"</td>";
            m += "<td style='text-align:center;'>"+addCommas(t.options.stats[h].s)+"</td>";
            m += "<td style='text-align:center;'>"+addCommas(t.options.stats[h].f)+"</td>";
            if (t.options.stats[h].s + t.options.stats[h].f == 0) var rate = 0;
            else var rate = Math.round(t.options.stats[h].s * 10000 / (t.options.stats[h].s + t.options.stats[h].f))/100;
            m += "<td style='text-align:center;'><b>"+rate+"%</b></td>";
            m += "<td style='text-align:center;'>"+addCommas(t.options.stats[h].e)+"</td>";
            if (z%2 == 1) m += "<td style='border-right:1px solid black;'></td><td></td>";
            if (z%2 == 0) m += "</tr>";
        }
        m+='</table>';
        m+='<br><div style="text-align:center;"><input type="submit" value="'+culang.craftStatsDelete+'" id="pbCraftStatReset"></div>';
        t.viewstats.getMainDiv().innerHTML = m;
        t.viewstats.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.viewCraftStats+'</div>';
        ById("pbCraftStatReset").addEventListener ('click', function (){
            for(var h in t.craftinfo) {
                t.options.stats[h] = {'e':0,'f':0,'s':0};
            }
            t.saveOptions();
            t.viewCraftStats();
        }, false);
        t.viewstats.show(true);
    },
    
    updateStat: function() {
        var t = Tabs.AutoCraft;
        var rownum = 0;
        function _row (name, row, noTotal, typee){
            if (rownum++ % 2)
                style = '';
            else
                style = ' style = "background: #e8e8e8"';
            var tot = 0;
            var m = [];
            m.push ('<TR style="background: #fff" align=right');
            m.push (style);
            m.push ('><TD');
            m.push (style);
            m.push ('><B>');
            m.push (name);
            m.push ('</td>');
            if (noTotal){
                m.push ('<TD');
                m.push (style);
                m.push ('>&nbsp;</td>');
            } else {
                for (i=0; i<row.length; i++)
                    tot += row[i];
                m.push ('<TD style="background: #ffc">');
                if (tot<0) {
                    m.push ("<SPAN class=boldRed>"+addCommas(tot)+"</span>");
                } else {
                    m.push (addCommas(tot));
                }
                m.push ('</td>');
            }
            for (i=0; i<row.length; i++){
                m.push ('<TD');
                m.push (style);
                m.push ('>');
                if (row[i]<5000) {
                    m.push ("<SPAN class=boldRed>"+addCommas(row[i])+"</span>");
                } else {
                    m.push (addCommas(row[i]));
                }
                m.push ('</td>');
            }

            m.push ('</tr>');
            return m.join('');
        }

        clearTimeout(t.timerStat);
        var str="<TABLE class=pdxTab cellpadding=0 cellspacing=0><TR  align=center><TD width=55 align=center></td><TD width=88 style='background: #ffc; font-size:150%' align=center><SPAN class=shadowCaps>"+culang.mainTotal+"</SPAN></td>";
        for(i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
            str += "<TD width=81><SPAN class=shadowCaps>"+ Cities.cities[i].name.substring(0,10) +"</SPAN></td>";
        }
        str+= '</tr>';
        rows = [];
        var now = unixTime();
        rows[0] = [];
        for(i=0; i<Cities.numCities; i++) {
            cityID = 'city'+ Cities.cities[i].id;
            rows[0][i] = parseInt(Seed.citystats[cityID].gold[0]);
        }
        for (r=1; r<6; r++){
            rows[r] = [];
            for(i=0; i<Cities.numCities; i++) {
                cityID = 'city'+ Cities.cities[i].id;
                if (r==5)
                    rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0]);
                else
                    rows[r][i] = parseInt(Seed.resources[cityID]['rec'+r][0] / 3600);
            }
        }
        str += _row ('<img height=18 src="'+IMGastone30+'">', rows[5], false, 0);
        str +='<tr style="background: #e8e8e8" align=right><td><img height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/items/70/3.jpg title="'+culang.mainCrafting+'"></b></td><td>&nbsp;</td>';
        for(i=0; i<Cities.numCities; i++) {
            var totTime = 0;
            if (Seed.queue_craft["city" + Cities.cities[i].id].length > 0) {
                var q=Seed.queue_craft["city" + Cities.cities[i].id][0];
                var totTime = 0;
                totTime = q.craftingEtaUnixTime - now;
                if (totTime < 0)
                    totTime = 0;
                if (getCityBuilding(Cities.cities[i].id,20).count>0 && totTime == 0)
                    affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                else
                    affuichage = timestr(totTime);
                str +="<td><span>"+ affuichage + "</span></td>";
            } else {
                affuichage = timestr(totTime);
                if (getCityBuilding(Cities.cities[i].id,20).count>0)
                    affuichage = '<SPAN class=boldRed><B>'+ timestr(totTime) +'</b></span>';
                str +="<td><span>"+affuichage+"</span></td>";
            }
        }
        str +="</tr>";
        
        //Bilder
        str +='<tr style="background: #e8e8e8" align=right><td>&nbsp;</td><td>&nbsp;</td>';
        for(i=0; i<Cities.numCities; i++) {
            if (Seed.queue_craft["city" + Cities.cities[i].id].length > 0) {
                var q=Seed.queue_craft["city" + Cities.cities[i].id][0];
                var h = t.craftitems[q.recipeId];
                var totTime = 0;
                totTime = q.craftingEtaUnixTime - now;
                if (totTime < 0) totTime = 0;
                if (totTime == 0) {
                    str +="<td>&nbsp;</td>";
                } else {
                    str +="<td align=right><img title='"+uW.itemlist["i"+h].name+"' width='40' src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/70/"+ h + ".jpg'></td>";
                }
            } else {
                str +="<td>&nbsp;</td>";
            }
        }
        str +="</tr></table>";
        t.id["KsCraftStat"].innerHTML=str;
        
        //Inventar
        for(var h in t.craftinfo) {
            t.id["KsCraft_nbi_"+h].innerHTML = parseIntNan(Seed.items["i"+h]);
        }

        //Throne
        var craftspeed = uW.cm.ThroneController.effectBonus(81);
        if (craftspeed > 200) {
            t.id["pbCraftSpeed"].innerHTML = '<b style="font-size:14px;">' +craftspeed + '% (max. 200%)</b><br>'+uW.g_js_strings.throneRoom.effectName_81;
        } else {
            t.id["pbCraftSpeed"].innerHTML = '<b style="font-size:14px;">' +craftspeed + '%</b><br>'+uW.g_js_strings.throneRoom.effectName_81;
        }

        if (t.options.throneCheck && Seed.throne.activeSlot != t.options.throneSet) {
            t.id["pbCraftSpeed"].style.backgroundColor = "maroon";
            t.id["pbCraftSpeed"].style.color = "white";
            t.id["pbCraftSpeed"].title = culang.falseThroneSet;
        } else {
            t.id["pbCraftSpeed"].style.backgroundColor = "white";
            t.id["pbCraftSpeed"].style.color = "black";
            t.id["pbCraftSpeed"].title = "";
        }
        
        t.timerStat = setTimeout(function() { t.updateStat(); }, 5000);
    },
    updateCraftnb : function() {
        var t = Tabs.AutoCraft;
        for(var h in t.craftinfo) {
            t.id["KsCraft_nb_"+h].value = parseIntNan(t.options.CraftingNb[h]) ;
        }
    },
    saveCraftState : function() {
        var t = Tabs.AutoCraft;
        for(var h in t.craftinfo) {
            t.options.CraftingNb[h] = parseIntNan(t.id["KsCraft_nb_"+h].value);
        }
        t.saveOptions();
    },
    toggleCraftStateRunning: function(){
        var t = Tabs.AutoCraft;
        obj = t.id['pbCraftRunning'];
        if (t.options.running == true) {
            t.options.running = false;
            t.saveCraftState();
            if (obj) obj.value = culang.craftButton+" = "+culang.buttonOFF;
            clearInterval(t.timer);
        } else {
            t.options.running = true;
            t.saveCraftState();
            if (obj) obj.value = culang.craftButton+" = "+culang.buttonON;
            t.timer=setInterval(t.Start,10000);
            t.Start();
        }
        t.updateCraftnb();
    },
    Start: function() {
        var t = Tabs.AutoCraft;
        if(!t.options.running) {
            clearInterval(t.timer);
            return;
        }
        if (t.numcity<Cities.numCities-1) {
            t.numcity++;
        } else {
            t.numcity=0;
        }
        var c=t.numcity;
        var cityId=Cities.cities[c].id;
        
        //Kein Fay-Turm?
        var fay = getCityBuilding(cityId,20);        
        var ret=fay.count;
        if (ret==0) {
            setTimeout(function() { t.Start(); }, 2000);
            return;
        }
        
        //Mindestens 2500 Aethersteine?
        var aether = parseIntNan(Seed.resources["city" + cityId]['rec5'][0]);
        if (aether<2500) {
            setTimeout(function() { t.Start(); }, 2000);
            return;
        }    
        
        //Wird gerade ein Teil gebaut?
        var i=Seed.queue_craft["city"+cityId];
        if(i.length>0) {
            var q=i[0];
            var totTime = 0;
            var now = unixTime();
            totTime = parseInt(q.craftingEtaUnixTime) + 3 - now;
            if (totTime > 0) {
                setTimeout(function() { t.Start(); }, 2000);
                return;
            }
        }        
        
        //Craftliste auslesen
        var tableau = [];
        for(var d in t.options.CraftingNb) {
            if (parseIntNan(t.options.CraftingNb[d])>0) {
                //Itemdaten
                var itemId = d;
                var recipeId = t.craftinfo[itemId].recipe_id;
                var category = t.craftinfo[itemId].category;
                var input = t.craftinfo[itemId].input;
                var requirements = t.craftinfo[itemId].requirements;
                    
                //Level des Fay-Towers?
                if (parseInt(fay.maxLevel) < parseInt(requirements.building)) {
                    continue;
                }
            
                //Genug Aethersteine?
                if (aether < parseInt(input.resources['1'])) {
                    continue;
                }
                
                //Genug Items vorhanden?
                if (input.items.length == undefined) {
                    var next = false;
                    for (i in input.items) {
                        var anz = parseInt(input.items[i]);            
                        if (!Seed.items['i'+i]) {
                            next = true;
                        }
                        if (Seed.items['i'+i] < anz) {
                            next = true;
                        }
                    }
                    if (next == true) continue;
                }

                //Falsches Throne-Set?
                if (t.options.throneCheck && Seed.throne.activeSlot != t.options.throneSet) {
                    //Einfaches Item?
                    if(t.options.SimpleItems && (itemId == 3000 || itemId == 3001 || itemId == 3003 || itemId == 3007 || itemId == 3008 || itemId == 3009)) {
                        //Einfache Items werden gecraftet
                    } else {
                        continue;
                    }
                }
                
                //Item in dieser Stadt erlaubt?
                if (t.options.CraftingNbC[itemId][c] == "n") {
                    continue;
                }
                
                //Item in List aufnehmen
                tableau.push(d);
            }
        }

        //Liste lehr?
        if (tableau.length == 0) {
            setTimeout(function() { t.Start(); }, 2000);
            return;
        }

        //Craftauftrag per Zufall
        var itemId = tableau[Math.floor(Math.random()*tableau.length)];
        var recipeId = t.craftinfo[itemId].recipe_id;
        var category = t.craftinfo[itemId].category;
        var input = t.craftinfo[itemId].input;
        var requirements = t.craftinfo[itemId].requirements;
        
        //Alles scheint OK
        if (!t.wait) {
            t.wait = true;
            t.CraftingItem(cityId,  itemId, recipeId, category);
        }
    },
    CraftingItem: function (currentcity, itemId, recipeId,category) {
        var t = Tabs.AutoCraft;
        var params = uW.Object.clone(uW.g_ajaxparams);
        params.action="craft";
        params.ctrl="Crafting";
        params.cityId=currentcity;
        params.insurance=false;
        params.itemId=itemId;
        params.recipeId=recipeId;
        params.categoryId=category;
        new AjaxRequest(uW.g_ajaxpath + "ajax/_dispatch.php" + uW.g_ajaxsuffix, { method: "post", parameters: params,loading: true,
            onSuccess: function (transport) {
                t.wait = false;
                var o=eval("("+transport.responseText+")");
                if(o.ok===true){
                    if (o.status=="error") {
                        actionLog(culang.mainCrafting, culang.mainError + ": <b>" + uW.itemlist["i"+itemId].name + '</b> in '+Cities.byID[currentcity].name + ' / <span style="color:red;">'+ o.errorMessage + '</span>'); //15.10.2012 Bommel
                        t.options.stats[itemId].e++;
                        t.saveOptions();
                    } else if(o.status=="failure"){
                        actionLog(culang.mainCrafting, culang.mainFailedAttempt + ": <b>" + uW.itemlist["i"+itemId].name + '</b> in '+Cities.byID[currentcity].name ); //15.10.2012 Bommel
                        t.options.stats[itemId].f++;
                        t.saveOptions();
                        //Items und Aether abziehen
                        var input = t.craftinfo[itemId].input;
                        var consolation = t.craftinfo[itemId].consolation_item_id;
                        Seed.resources["city" + currentcity]['rec5'][0] = Seed.resources["city" + currentcity]['rec5'][0] - parseInt(input.resources['1']);
                        if (input.items.length == undefined) {
                            for (i in input.items) {
                                var anz = parseInt(input.items[i]);
                                Seed.items['i'+i] = Seed.items['i'+i] - anz;
                                uW.ksoItems[i].subtract(anz);
                                if (Seed.items['i'+i] < 0) {
                                    Seed.items['i'+i] = 0;
                                }
                            }
                        }
                        //Erstattung bei Fehler
                        if (consolation != 0) {
                            Seed.items['i'+consolation] = Seed.items['i'+consolation] + 1;
                            uW.ksoItems[consolation].add(1);
                        }
                        t.updateCraftnb();
                    } else if (o.status=="success"){
                        actionLog(culang.mainCrafting, culang.mainSuccessfulAttempt + ": <b>" + unsafeWindow.itemlist["i"+itemId].name + '</b> in '+Cities.byID[currentcity].name ); //15.10.2012 Bommel
                        t.options.stats[itemId].s++;
                        t.saveOptions();
                        t.options.CraftingNb[itemId] =  t.options.CraftingNb[itemId] - 1;
                        Seed.queue_craft["city"+currentcity]=[];
                        var n={};
                        n.recipeId=recipeId;
                        n.craftingUnixTime=o.time.startTime;
                        n.craftingEtaUnixTime=o.time.endTime;
                        n.craftingId=o.craftingId;
                        n.categoryId=null;
                        n.recipeIndex=null;
                        Seed.queue_craft["city"+currentcity].push(n);
                        //Items und Aether abziehen
                        var input = t.craftinfo[itemId].input;
                        var consolation = t.craftinfo[itemId].consolation_item_id;
                        Seed.resources["city" + currentcity]['rec5'][0] = Seed.resources["city" + currentcity]['rec5'][0] - parseInt(input.resources['1']);
                        if (input.items.length == undefined) {
                            for (i in input.items) {
                                var anz = parseInt(input.items[i]);
                                Seed.items['i'+i] = Seed.items['i'+i] - anz;
                                uW.ksoItems[i].subtract(anz);
                                if (Seed.items['i'+i] < 0) {
                                    Seed.items['i'+i] = 0;
                                }
                            }
                        }
                        t.updateCraftnb();
                    }
                }
            },
            onFailure: function () {  
                t.wait = false;
                actionLog(culang.mainCrafting, culang.mainFatalAjaxError + ":  <b>" + uW.itemlist["i"+itemId].name + '</b> in '+Cities.byID[currentcity].name ); //15.10.2012 Bommel
            }
        });
    },
    show : function (){
        var t = Tabs.AutoCraft;
        clearTimeout(t.timerStat);
        t.updateStat();
    },
    hide: function(){
        var t = Tabs.AutoCraft;
        clearTimeout(t.timerStat);
    },
};
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Options.js">
/************************************************************************************
 *                        KOC POWER - TABS OPTIONS                                    *
 ************************************************************************************/
Tabs.Options = {
    tabOrder: TabOptions.toOptions,
    tabLabel: culang.tabLabelOptions,
    cont : null,
    state : null,
    fixAvailable : {},
    soundRepeatTimer : null,
    soundStopTimer : null,
    secondTimer : null,
    soundPlaying : false,
    
    show : function (){
        var t = Tabs.Options;
    },

    stopSoundAlerts : function (){
        var t = Tabs.Options;
        obj = ById('optionsSoundStop');
        t.mss.stop (1);
        clearTimeout (t.soundStopTimer);
        clearTimeout (t.soundRepeatTimer);
        ById('optionsSoundStop').disabled = true;
        Options.alertSound.alarmActive = false;
        Options.alertSound.expireTime = 0;
        setTimeout(function() {
            if (ById('botowertab'))
                ById('botowertab').style.display="none";
        },2000);
    },
    e_soundFileLoaded : function (chan, isError){
        if (chan != 1)
            return;
        if (isError)
            ById('optionsLoadSWF').innerHTML = ''+culang.optionsLoadingSWFerror+'';
        else
            ById('optionsLoadSWF').innerHTML = ''+culang.optionsChargement+'';
    },
    playSound : function (doRepeats){
        var t = Tabs.Options;
        ById('optionsSoundStop').disabled = false;
        clearTimeout (t.soundStopTimer);
        clearTimeout (t.soundRepeatTimer);
        t.mss.play(1, 0);
        t.soundStopTimer = setTimeout (function(){t.mss.stop(1); t.e_soundFinished(1)}, Options.alertSound.playLength*1000);
        if (doRepeats && Options.alertSound.repeat)
            t.soundRepeatTimer = setTimeout (function (){t.playSound(true)}, Options.alertSound.repeatDelay*60000);
        else
            Options.alertSound.alarmActive = false;
    },
    e_soundFinished : function (chan){
        var t = Tabs.Options;
        if (chan != 1)
            return;
        if (!Options.alertSound.alarmActive){
            ById('optionsSoundStop').disabled = true;
        }
    },
    soundTheAlert : function (m){
        var t = Tabs.Options;

        var totTroops = 0;
        for (k in m.unts) {
            var uid = parseInt(k.substr(1));
            totTroops += m.unts[k];
        }


        Options.alertSound.alarmActive = true;
        t.playSound(true);
    },


    hide : function (){
        var t = Tabs.Options;
    },
    togOpt : function (checkboxId, optionName, callEnable, callIsAvailable){
        var t = Tabs.Options;
        var checkbox = ById(checkboxId);

        if (callIsAvailable && callIsAvailable()==false){
            checkbox.disabled = true;
            return;
        }
        if (Options[optionName])
            checkbox.checked = true;
        checkbox.addEventListener ('change', new eventToggle(checkboxId, optionName, callEnable).handler, false);
        function eventToggle (checkboxId, optionName, callOnChange){
            this.handler = handler;
            var optName = optionName;
            var callback = callOnChange;
            function handler(event){
                Options[optionName] = this.checked;
                saveOptions();
                if (callback != null)
                    callback (this.checked);
            }
        }
    },


    init : function (div){
        var t = Tabs.Options;
        t.cont = div;
        if (Options.DeleteTimerMinute===undefined) Options.DeleteTimerMinute=5;
        if (Options.NewTabURL==undefined) Options.NewTabURL=homePage;
        if (Options.alertConfig.throneSet == undefined) Options.alertConfig.throneSet = 1;
        if (Options.alertConfig.throneSetRet == undefined) Options.alertConfig.throneSetRet = 1;
        if (Options.alertConfig.returnThroneMin == undefined) Options.alertConfig.returnThroneMin = 60;
        
        setTimeout(function() {
            AddTowerTab(' <img height="48" src="http://kofc.god-like.info/multi/img/animated_siren.gif" title="'+culang.optionsStopSound+'"> ', t.stopSoundAlerts, 'botowertab');
        }, 1000);

        var chat = ById('kocmain_bottom').childNodes[1];
        if (chat) {
            var channel_input = nHtml.FindByXPath(chat,".//div[contains(@class,'mod_comm_forum')]");
            var ab = document.createElement('a');
            ab.className="mod_comm_set";
            channel_input.appendChild(ab);
            ab.innerHTML=""+culang.mainSmileys+"";
            ab.addEventListener ('click', function() {
                t.EmoHelp();
            },false);
            if (chat && Options.pdxLangFlag) {
            var cd = document.createElement('a');
            cd.className="mod_comm_flag";
            channel_input.appendChild(cd);    
            cd.innerHTML='<img height=16 src="http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/'+LangOptions.culang+'-24x24.png" title="'+culang.KsRunningLanguage+'">';
            cd.addEventListener ('click', function() {
                // t.EmoHelp();
            },false);
        }
        if (chat && Options.pdxHyperlinks) {
            var cd = document.createElement('a');
            cd.className="mod_comm_links";
            channel_input.appendChild(cd);    
            cd.innerHTML='<a href="#" onclick="document.getElementById(\'pdxInfoBoxShow\').style.display=(document.getElementById(\'pdxInfoBoxShow\').style.display== \'block\')?\'none\':\'block\';"><img src="'+IMGksMini+'" alt="KoC Scripts" width="16" height="16" border="0" title="'+culang.optionsHyperlinksButtonTitle+'"> </a>\
            <DIV id="pdxInfoBoxShow" style="display:none;">\
            <div class=pdxInfoBox>\
            <a href="http://kocbot.webs.com" target="_blank"><img src="'+IMGpdxTeam+'" alt="KoC Scripts" width="32" height="32" border="0" title="'+culang.KsInfoBoxHomePageNote+'"></a>\
            <a href="http://kocbot.webs.com" target="_blank"><img src="'+IMGteamLink+'" alt="KS Team" width="32" height="32" border="0" title="'+culang.KsInfoBoxTeamNote+'"></a>\
            <a href="https://www.facebook.com" target="_blank"><img src="'+IMGdevGroup+'" alt="KS DevGroup" width="32" height="24" border="0" title="'+culang.KsInfoBoxDevGroupNote+'"></a>\
            <a href="http://kocbot.webs.com" target="_blank"><img src="'+IMGFBGroup+'" alt="Facebook Groups" width="32" height="32" border="0" title="'+culang.KsInfoBoxFacebookNote+'"></a>\
            <a href="http://code.google.com/p/mad-hatters-magic/" target="_blank"><img src="'+IMGgooglecode+'" alt="googlecode" width="32" height="32" border="0" title="'+culang.KsInfoBoxGCNote+'"></a>\
            <a href="http://userscripts.org" target="_blank"><img src="'+IMGuserscripts+'" alt="Userscripts" width="32" height="32" border="0" title="'+culang.KsInfoBoxUserscriptsNote+'"></a>\
            <a href="http://code.google.com/p/mad-hatters-magic/issues/entry" target="_blank"><img src="'+IMGreport+'" alt="Report" width="32" height="32" border="0" title="'+culang.KsInfoBoxReportNote+'"></a>\
            <a href="http://userscripts.org" target="_blank"><img src="'+IMGreview+'" alt="Review" width="32" height="32" border="0" title="'+culang.KsInfoBoxReviewNote+'"></a>\
            <a href="http://www.mozilla.org/firefox/" target="_blank"><img src="'+IMGfirefox+'" alt="Firefox" width="32" height="32" border="0" title="'+culang.KsInfoBoxFirefoxNote+'"></a>\
            <a href="https://addons.mozilla.org/de/firefox/addon/greasemonkey/" target="_blank"><img src="'+IMGgreasemonkey+'" alt="Greasemonkey" width="32" height="32" border="0" title="'+culang.KsInfoBoxGreasemonkeyNote+'"></a>\
            <a href="https://addons.mozilla.org/de/firefox/addon/scriptish/" target="_blank"><img src="'+IMGscriptish+'" alt="Scriptish" width="32" height="32" border="0" title="'+culang.KsInfoBoxScriptishNote+'"></a>\
            <a href="http://www.java.com/de/download/installed.jsp" target="_blank"><img src="'+IMGjava+'" alt="Java" width="32" height="32" border="0" title="'+culang.KsInfoBoxJavaNote+'"></a>\
            <a href="http://www.adobe.com/de/software/flash/about/" target="_blank"><img src="'+IMGflash+'" alt="FlashPlayer" width="32" height="32" border="0" title="'+culang.KsInfoBoxFlashNote+'"> </a>\
            <a href="http://www.4loot.com/?id=264098&src=em" target="_blank">  <img src="'+IMG4loot+'" alt="4Loot" width="30" height="30" border="0" title="'+culang.KsInfoBox4LootNote+'"> </a>\
            </div>\
            </div>';

            cd.addEventListener ('click', function() {
                // t.EmoHelp();
            },false);
        }
    
        } try {
            var html = '<DIV style="margin-top:5px; max-height:'+(Options.HauteurBoite-45)+'px; overflow:auto;">';
            html += '<TABLE class=pdxTab>\
            <TR><TD>&nbsp;</td><TD><B>'+culang.mainLangpacks+'</B>: <select id=pbLang '+(LangOptions.culang==0?'DISABLED':'')+'/>\
            <option value=0 >-- '+culang.mainSelect+' --</option>';
            for (var i in LangOptions.langpacks) {
                if(i == LangOptions.culang)
                    html += '<option value="'+i+'" selected="selected">'+i+'</option>'; // Load Previous langpack Selection
                else
                    html += '<option value="'+i+'">'+i+'</option>\
            ';
            }
            html += '</select><sup><b> '+culang.mainVersion+'</b>: <span class=boldRed>'+LangpackVersion+'</span></sup><br>\
            <INPUT id=pbupdatelanglist type=submit value='+langpack.buttonUpdate+'>\
            <b><sup><span class=boldRed><u>'+culang.mainImportant+'</u></span>:</sup> <span class=helpText>'+ culang.optionsLangpackNote+'</span></td>\
            <TD colspan="2"><a href="http://koc.god-like.org" target="_blank" title="'+culang.optionsVisitKS+'"><img height="20" src="'+IMGpdxTeam+'"></a><sup><b><u>KoC Power - Multilang</u></b><img height=16 width=16 src="http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/'+LangOptions.culang+'-24x24.png" title="Du Benutz zur Zeit die Deutsche version vergiss nicht das Spiel selbst auch auf die gleiche Sprache einszustellen!"></sup><BR><sup>'+culang.optionsKsRunning+' "<a href="'+KsScriptPage+'" target="_blank" title="'+culang.optionsKsRunningNote+' '+KsScriptRunning+' '+culang.optionsKsRunningNote2+'">'+KsScriptRunning+'</a>" </sup> <b>'+culang.mainVersion+'</b>: <span class=boldRed>'+Version+' <a target="_blank" href="'+KsInstallLink+'" title="'+culang.ksInstallLatestNote+'"></span> <img height="16" src="'+IMGlatestVersion+'"><BR></a><sup>'+KsLatestVersion+'</sup></td></tr>\
            <TR><TD colspan="2"><strong>'+culang.optionsChangelogFiles+'</strong></td></tr></table>';

            /* powerTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'powerTabOptions\').style.display=(document.getElementById(\'powerTabOptions\').style.display== \'none\')?\'block\':\'none\';">'+culang.optionsHeadMulti+'</a></div>';
                html += '<DIV id="powerTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TR><TD width=5%><INPUT id=ptAllowWinMove type=checkbox /></td><TD width=27%>'+culang.optionsWinDragDrop+'</td>\
                <TR><TD><INPUT id=pbEveryEnable type=checkbox /></td><TD>'+culang.optionsAutoRefreshIntervall+' <INPUT id=pbeverymins type=text size=2 maxlength=3 \> '+culang.optionsAutoRefreshIntervall2+' </td>\
                <TR><TD><INPUT id=KsgmtClock type=checkbox '+ (Options.gmtClock?'CHECKED ':'') +'/></td><TD> '+culang.optionsGMTClock+' </td><TD></td></tr>\
                <TR><TD><INPUT id=KsWatchEnable type=checkbox '+ (GlobalOptions.pbWatchdog?'CHECKED ':'') +'/></td><TD>'+culang.optionsRefreshIfInaktive+'</td></tr>\
                <TR><TD><INPUT id=togDeleteButtons type=checkbox '+ (Options.deleteButtons?'CHECKED ':'') +'/></td><TD>'+culang.delPromoButtons+'</td></tr>\
                <TR><TD><INPUT id=togmerlinClose type=checkbox '+ (Options.merlinClose?'CHECKED ':'') +'/></td><TD>'+culang.merlinClose+'</td></tr>\
                <TR><TD><INPUT id=pbsendmeaway type=checkbox '+ (GlobalOptions.pbNoMoreKabam?'CHECKED ':'')+'/></td><TD>'+culang.optionsAwayOnKabam+'</td></tr>\
                <TR><TD><INPUT id=togEnableButtler type=checkbox '+ (Options.enableButtler?'CHECKED ':'') +'/></td><TD colspan=3>'+culang.optionsEnableButtler+'</tr>\
                <TR><TD><INPUT id=togKsInfoBox type=checkbox /></td><TD colspan=3>'+culang.optionsInfoBox+'</td></tr>\
                <TR><TD><INPUT id=togEnableBrowserBG type=checkbox '+ (GlobalOptions.enableBrowserBG?'CHECKED ':'') +'/></td><td><span title="'+culang.optionsBrowserBGNote+'">'+ htmlSelector({backCol:''+culang.optionsBrowserBGColor+'', backImg:''+culang.optionsBrowserBGImage+'' }, GlobalOptions.backStyle,'id=KsBackSelector') +'</span> - '+culang.optionsBrowserBGImageURL+' <INPUT id=KsBackgroundImage type=text size=14 maxlength=1000 value="'+GlobalOptions.bgImg+'" title="'+culang.optionsBrowserBGImageNote+'">  '+culang.optionsBrowserBGorColor+' <INPUT id=KsBackgroundColor type=text size=7 maxlength=7 value="'+GlobalOptions.bgCol+'" title="'+culang.optionsBrowserBGColorNote+'"> <td></tr></table>';
                html += '</div>';
            }

            /* tabsTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'tabsTabOptions\').style.display=(document.getElementById(\'tabsTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadTabs+'</a></div>';
                html += '<DIV id="tabsTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TR><TD><INPUT id=togPDXMenuLeft type=checkbox /></td><TD colspan=3>'+culang.optionsPowerMenuLeft+'</td></tr>\
                <TR><TD><INPUT id=KsNewTab type=checkbox /></td><TD colspan=3>'+culang.optionsUserTab+': '+culang.mainURL+': <input type=text size=20 value="'+Options.NewTabURL+'" id=KsNewTabURL> '+culang.optionsTabName+': <input type=text size=10 maxlength=12 id=KsNewTabName value="'+Options.NewTabName+'"></td></tr>\
                <TR><TD><INPUT id=KsIdHomeTab type=checkbox /></td><TD colspan=3>'+culang.optionsKsTab+'</tr></table>';
                html += '<DIV class=pdxStat2><a href="#" onclick="document.getElementById(\'tabsTabOrderOptions\').style.display=(document.getElementById(\'tabsTabOrderOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadTabsOrder+'</a> (POWER)</div>';
                html += '<DIV id="tabsTabOrderOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <tr><td width="12"><INPUT id=KsToOverview type=text size=2 maxlength=2></td><td>'+culang.tabLabelOverview+'</td></tr>\
                <tr><td><INPUT id=KsToReports type=text size=2 maxlength=2></td><td>'+culang.mainReports+'</td></tr>\
                <tr><td><INPUT id=KsToMarches type=text size=2 maxlength=2></td><td>'+culang.tabLabelMarch+'</td></tr>\
                <tr><td><INPUT id=KsToTrain type=text size=2 maxlength=2></td><td>'+culang.tabLabelTrain+'</td></tr>\
                <tr><td><INPUT id=KsToAutoTrain type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoTrain+'</td></tr>\
                <tr><td><INPUT id=KsToThroneStuff type=text size=2 maxlength=2></td><td>'+culang.tabLabelThroneStuff+'</td></tr>\
                <tr><td><INPUT id=KsToSearch type=text size=2 maxlength=2></td><td>'+culang.tabLabelSearch+'</td></tr>\
                <tr><td><INPUT id=KsToPlayer type=text size=2 maxlength=2></td><td>'+culang.mainPlayer+'</td></tr>\
                <tr><td><INPUT id=KsToBuild type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoBuild+'</td></tr>\
                <tr><td><INPUT id=KsToTransport type=text size=2 maxlength=2></td><td>'+culang.mainTransport+'</td></tr>\
                <tr><td><INPUT id=KsToReassign type=text size=2 maxlength=2></td><td>'+culang.mainReassign+'</td></tr>\
                <tr><td><INPUT id=KsToAutoCraft type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoCraft+'</td></tr>\
                <tr><td><INPUT id=KsToFarm type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoFarm+'</td></tr>\
                <tr><td><INPUT id=KsToCrest type=text size=2 maxlength=2></td><td>'+culang.tabLabelCrest+'</td></tr>\
                <tr><td><INPUT id=KsToDarkForest type=text size=2 maxlength=2></td><td>'+culang.mainDarkForest+'</td></tr>\
                <tr><td><INPUT id=KsToRaid type=text size=2 maxlength=2></td><td>'+culang.mainRaid+'</td></tr>\
                <tr><td><INPUT id=KsToApothecary type=text size=2 maxlength=2></td><td>'+culang.tabLabelApothecary+'</td></tr>\
                <tr><td><INPUT id=KsToScoutAlliance type=text size=2 maxlength=2></td><td>'+culang.tabLabelAutoScout+'</td></tr>\
                <tr><td><INPUT id=KsToWild type=text size=2 maxlength=2></td><td>'+culang.tabLabelWild+'</td></tr>\
                <tr><td><INPUT id=KsToKnights type=text size=2 maxlength=2></td><td>'+culang.tabLabelKnights+'</td></tr>\
                <tr><td><INPUT id=KsToOptions type=text size=2 maxlength=2></td><td>'+culang.tabLabelOptions+'</td></tr>\
                <tr><td><INPUT id=KsToUserTab type=text size=2 maxlength=2></td><td>'+Options.NewTabName+'</td></tr>\
                <tr><td><INPUT id=KsToKoCScripts type=text size=2 maxlength=2></td><td>KoC Scripts</td></tr>\
                <tr><td colspan=2>'+ strButton20(culang.buttonResetTabOrder, 'id=togResetStyleOpt') +'</td></tr>\
                </table>';
                html += '</div></div>';
            }

            /* chatTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'chatTabOptions\').style.display=(document.getElementById(\'chatTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadChat+'</a></div>';
                html += '<DIV id="chatTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TR><TD><input  type=checkbox id=pbChatREnable /></td><TD width="696">'+culang.optionsChatRight+'</td></tr>\
                <TR><TD><INPUT id=PubReq type=checkbox '+ (GlobalOptions.autoPublishGamePopups?'CHECKED ':'') +'/></td><TD title="'+culang.optionsAutoPublishOnFacebookNote2+'">'+culang.optionsAutoPublishOnFacebook+' '+ htmlSelector({0:'-- '+culang.mainSelect+' --', 80:''+culang.optionsAutoPublishOnFacebookEveryone+'', 50:''+culang.optionsAutoPublishOnFacebookFriendsOfFriends+'', 40:''+culang.optionsAutoPublishOnFacebookFriendsOnly+'', 10:''+culang.optionsAutoPublishOnFacebookOnlyMe+''},GlobalOptions.autoPublishPrivacySetting,'id=selectprivacymode') +' <sup>(<span class="boldRed">'+culang.optionsAutoPublishOnFacebookNote+'</span>)</sup></td></tr>\
                <TR><TD><INPUT id=ptEnableFoodWarnTchat type=checkbox /></td><TD>'+culang.optionsChatLowFood+' - '+culang.mainIntervall+': <INPUT type=text id=optFoodChatHours value="'+ Options.foodChatWarnHours +'" size=2></td></tr>\
                <TR><TD><INPUT id=HelReq type=checkbox /></td><TD>'+culang.optionsChatHelpReq+'</td></tr>\
                <TR><TD><INPUT id=DelReq type=checkbox /></td><TD>'+culang.optionsChatDelReq+'</td></tr>\
                <TR><TD><INPUT id=DelRules type=checkbox /></td><TD>'+culang.optionsChatDelRules+'</td></tr>\
                <TR><TD><INPUT id=togChatStuff type=checkbox /></td><TD>'+culang.optionsChatExtras+'</td></tr>\
                <TR><TD><INPUT id=KsSmiley type=checkbox /></td><TD>'+culang.mainSmileys+' <INPUT id=EmoHelp type=submit value="'+culang.buttonHelp+'"></td></tr>\
                <TR><TD><INPUT id=togShowMultiUpdateNote type=checkbox '+ (Options.showMultiUpdateNote?'CHECKED ':'') +'/></td><TD colspan=3>'+ htmlSelector({updateFull:culang.optionsPostMulitUpdateShowFull, updateTextImageLike:culang.optionsPostMulitUpdateShowTextImageLike, updateTextImage:culang.optionsPostMulitUpdateShowTextImage, updateText:culang.optionsPostMulitUpdateShowText }, GlobalOptions.updateChatNote,'id=KsUpdateChatNoteSel') +' '+culang.optionsShowMultiUpdateCmd+'</td></tr>\
                <TR><TD><INPUT id=togPostMultiUpdate type=checkbox '+ (Options.postMultiUpdate?'CHECKED ':'') +'/></td><TD colspan=3>'+culang.optionsPostMulitUpdate+'</td></tr>\
                <TR><TD colspan=4>'+culang.optionsPostMulitUpdateSound+' '+culang.mainVolume+' <INPUT id=togMultiUpdateSoundVol size=1 maxlength=1 type=textbox value="'+ Options.multiUpdateSoundVol +'" /> '+culang.optionsPostMulitUpdateSoundAutoPlay+' <INPUT id=togMultiUpdateSoundEnable size=1 maxlength=1 type=textbox value="'+ Options.multiUpdateSoundEnable +'" /> 0 = '+culang.buttonOFF+' 1 = '+culang.buttonON+'</td></tr>\
                </table>';
                html += '</div>';
            }

            /* colorsTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'colorsTabOptions\').style.display=(document.getElementById(\'colorsTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadColors+'</a> (<a target=_blank href="http://kofc.god-like.info/colors.html" title="'+culang.optionsChatSelectColorNote+'">'+culang.optionsChatSelectColor+'</a>)</div>';
                html += '<DIV id="colorsTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatScoutAlert style="background-color:'+Colors.ChatEcl+'" type=text size=7 maxlength=7 value="'+Colors.ChatEcl+'"> '+culang.optionsChatScoutBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatScoutAlertFont style="background-color:'+Colors.ChatEclFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatEclFont+'"></td></tr>\
                <TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatAtt style="background-color:'+Colors.ChatAtt+'" type=text size=7 maxlength=7 value="'+Colors.ChatAtt+'"> '+culang.optionsChatAttackBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatAttFont style="background-color:'+Colors.ChatAttFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatAttFont+'"></td></tr>\
                <TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatWildAtt style="background-color:'+Colors.ChatWildAtt+'" type=text size=7 maxlength=7 value="'+Colors.ChatWildAtt+'"> '+culang.optionsChatWildAttackBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatWildAttFont style="background-color:'+Colors.ChatWildAttFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatWildAttFont+'"></td></tr>\
                <TR><TD>&nbsp;&nbsp;&nbsp;</td><TD>&nbsp;<INPUT id=togChatLowFood style="background-color:'+Colors.ChatLowFood+'" type=text size=7 maxlength=7 value="'+Colors.ChatLowFood+'"> '+culang.optionsChatLowFoodBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatLowFoodFont style="background-color:'+Colors.ChatLowFoodFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatLowFoodFont+'"></td></tr>\
                <TR><TD>&nbsp;</td><TD><INPUT id=togChatGlo style="background-color:'+Colors.ChatGlo+'" type=text size=7 maxlength=7 value="'+Colors.ChatGlo+'"> '+culang.optionsChatGlobalBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatGloFont style="background-color:'+Colors.ChatGloFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatGloFont+'"></td></tr>\
                <TR><TD>&nbsp;</td><TD><INPUT id=togChatAlliance style="background-color:'+Colors.ChatAlliance+'" type=text size=7 maxlength=7 value="'+Colors.ChatAlliance+'"> '+culang.optionsChatAllianceBG+'</td><td> - '+culang.optionsChatFontcolor+' <INPUT id=togChatAllianceFont style="background-color:'+Colors.ChatAllianceFont+'" type=text size=7 maxlength=7 value="'+Colors.ChatAllianceFont+'"></td></tr>\
                <TR><TD colspan=2><INPUT id=KsChatLeader type=checkbox /> '+culang.optionsChatLeaderBG+'</td></tr>\
                <TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatC style="background-color:'+Colors.ChatChancy+'" type=text size=7 maxlength=7 value="'+Colors.ChatChancy+'"> '+culang.mainChancellor+'</td></tr>\
                <TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatVC style="background-color:'+Colors.ChatVC+'" type=text size=7 maxlength=7 value="'+Colors.ChatVC+'"> '+culang.mainViceChancellor+' </td></tr>\
                <TR><TD>&nbsp;&nbsp;</td><TD><INPUT id=togChatLeaders style="background-color:'+Colors.ChatLeaders+'" type=text size=7 maxlength=7 value="'+Colors.ChatLeaders+'"> '+culang.mainOfficer+' </td></tr>\
                </table>\
                <TABLE class=pdxTab>\
                <TR><td>'+culang.optionsColorsMainTitle+'</td><TD><INPUT id=togMainTitle style="background-color:'+Colors.MainTitle+'" type=text size=7 maxlength=7 value="'+Colors.MainTitle+'"> '+culang.optionsChatFontcolor+' - <INPUT id=togMainTitleHover style="background-color:'+Colors.MainTitleHover+'" type=text size=7 maxlength=7 value="'+Colors.MainTitleHover+'"> '+culang.optionsColorsHover+' <INPUT id=togMainTitleBackground style="background-color:'+Colors.MainTitleBackground+'" type=text size=7 maxlength=7 value="'+Colors.MainTitleBackground+'"> '+culang.optionsColorsBackground+'</td></tr>\
                <TR><td>'+culang.optionsColorsSubMainTitle+'</td><TD><INPUT id=togMainTitle2 style="background-color:'+Colors.MainTitle2+'" type=text size=7 maxlength=7 value="'+Colors.MainTitle2+'"> '+culang.optionsChatFontcolor+' - <INPUT id=togMainTitle2Hover style="background-color:'+Colors.MainTitle2Hover+'" type=text size=7 maxlength=7 value="'+Colors.MainTitle2Hover+'"> '+culang.optionsColorsHover+' <INPUT id=togMainTitle2Background style="background-color:'+Colors.MainTitle2Background+'" type=text size=7 maxlength=7 value="'+Colors.MainTitle2Background+'"> '+culang.optionsColorsBackground+'</td></tr>\
                </table>';
                html += '<DIV class=pdxStat2><a href="#" onclick="document.getElementById(\'colorsChatTabOptions\').style.display=(document.getElementById(\'colorsChatTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsColorsHead+'</a></div>';
                html += '<DIV id="colorsChatTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\<TR><TD><b><u>'+culang.mainPlayer+'</u></b> </td><TD><b><u>'+culang.optionsColorsColor+'</u></b> </td><TD width="153" ><b><u>'+culang.mainName+'</u></b></td><TD><b><u>'+culang.mainPlayer+'</u></b> </td><TD><b><u>'+culang.optionsColorsColor+'</u></b> </td><TD width="144" ><u><b>'+culang.mainName+'</b></u></td></tr>        <TR><TD width="200" ><INPUT  type=checkbox id=ptEnableUserName1 />  '+culang.mainPlayer+' #1 </td><TD  width="44" ><INPUT  style="background:'+Colors.userBG1+'" type=text id=toguserBG1 value="'+Colors.userBG1+'" size=7 maxlength=7></td><TD><input type=text id=togcolorUserName1 value="'+ Options.userName1 +'"></td><TD width="200" ><INPUT  type=checkbox id=ptEnableUserName16 /> '+culang.mainPlayer+' #16 </td><TD  width="44" ><INPUT  style="background:'+Colors.userBG16+'" type=text id=toguserBG16 value="'+Colors.userBG16+'" size=7 maxlength=7></td><TD><input type=text id=togcolorUserName16 value="'+ Options.userName16 +'"></td></tr>        <TR><TD ><INPUT  type=checkbox id=ptEnableUserName2 /> '+culang.mainPlayer+' #2 </td><TD  ><INPUT style="background:'+Colors.userBG2+'" type=text id=toguserBG2 value="'+Colors.userBG2+'" size=7 maxlength=7></td><TD ><INPUT  type=text id=togcolorUserName2 value="'+ Options.userName2 +'"></td><TD ><INPUT  type=checkbox id=ptEnableUserName17 />'+culang.mainPlayer+' #17 </td><TD ><INPUT  style="background:'+Colors.userBG17+'"  type=text id=toguserBG17 value="'+Colors.userBG17+'" size=7 maxlength=7></td><TD ><INPUT  type=text id=togcolorUserName17 value="'+ Options.userName17 +'"></td></tr>        <TR ><TD ><INPUT type=checkbox id=ptEnableUserName3 /> '+culang.mainPlayer+' #3</td><TD ><INPUT style="background:'+Colors.userBG3+'" type=text id=toguserBG3 value="'+Colors.userBG3+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName3 value="'+ Options.userName3 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName18 /> '+culang.mainPlayer+' #18 </td><TD ><INPUT style="background:'+Colors.userBG18+'" type=text id=toguserBG18 value="'+Colors.userBG18+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName18 value="'+ Options.userName18 +'"></td></tr>        <TR ><TD ><INPUT type=checkbox id=ptEnableUserName4 /> '+culang.mainPlayer+' #4 </td><TD  ><INPUT style="background:'+Colors.userBG4+'" type=text id=toguserBG4 value="'+Colors.userBG4+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName4 value="'+ Options.userName4 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName19 />'+culang.mainPlayer+' #19 </td><TD><INPUT  style="background:'+Colors.userBG19+'"  type=text id=toguserBG19 value="'+Colors.userBG19+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName19 value="'+ Options.userName19+'"></td></tr>        <TR ><TD><INPUT type=checkbox id=ptEnableUserName5 /> '+culang.mainPlayer+' #5 </td><TD ><INPUT style="background:'+Colors.userBG5+'" type=text id=toguserBG5 value="'+Colors.userBG5+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName5 value="'+ Options.userName5 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName20 />'+culang.mainPlayer+' #20 </td><TD ><INPUT style="background:'+Colors.userBG20+'" type=text id=toguserBG20 value="'+Colors.userBG20+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName20 value="'+ Options.userName20 +'"></td></tr>        <TR ><TD ><INPUT type=checkbox id=ptEnableUserName6 /> '+culang.mainPlayer+' #6 </td><TD ><INPUT style="background:'+Colors.userBG6+'" type=text id=toguserBG6 value="'+Colors.userBG6+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName6 value="'+ Options.userName6 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName21 /> '+culang.mainPlayer+' #21 </td><TD ><INPUT style="background:'+Colors.userBG21+'" type=text id=toguserBG21 value="'+Colors.userBG21+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName21 value="'+ Options.userName21 +'"></td></tr>        <TR ><TD><INPUT  type=checkbox id=ptEnableUserName7 /> '+culang.mainPlayer+' #7 </td><TD ><INPUT style="background:'+Colors.userBG7+'" type=text id=toguserBG7 value="'+Colors.userBG7+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName7 value="'+ Options.userName7 +'"></td><TD><INPUT  type=checkbox id=ptEnableUserName22 /> '+culang.mainPlayer+' #22</td><TD ><INPUT style="background:'+Colors.userBG22+'" type=text id=toguserBG22 value="'+Colors.userBG22+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName22 value="'+ Options.userName22 +'"></td></tr>        <TR ><TD ><INPUT type=checkbox id=ptEnableUserName8 /> '+culang.mainPlayer+' #8 </td><TD ><INPUT style="background:'+Colors.userBG8+'" type=text id=toguserBG8 value="'+Colors.userBG8+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName8 value="'+ Options.userName8 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName23 />     '+culang.mainPlayer+' #23 </td><TD ><INPUT style="background:'+Colors.userBG23+'" type=text id=toguserBG23 value="'+Colors.userBG23+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName23 value="'+ Options.userName23 +'"></td></tr>        <TR ><TD ><INPUT type=checkbox id=ptEnableUserName9 /> '+culang.mainPlayer+' #9 </td><TD ><INPUT style="background:'+Colors.userBG9+'" type=text id=toguserBG9 value="'+Colors.userBG9+'" size=7 maxlength=7></td><TD ><input type=text id=togcolorUserName9 value="'+ Options.userName9 +'"></td><TD ><INPUT type=checkbox id=ptEnableUserName24 />     '+culang.mainPlayer+' #24 </td><TD ><INPUT style="background:'+Colors.userBG24+'" type=text id=toguserBG24 value="'+Colors.userBG24+'" size=7 maxlength=7></td><TD ><input type=text id=togcolorUserName24 value="'+ Options.userName24 +'"></td></tr>        <TR ><TD><INPUT type=checkbox id=ptEnableUserName10 /> '+culang.mainPlayer+' #10 </td><TD ><INPUT style="background:'+Colors.userBG10+'" type=text id=toguserBG10 value="'+Colors.userBG10+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName10 value="'+ Options.userName10 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName25 /> '+culang.mainPlayer+' #25 </td><TD ><INPUT style="background:'+Colors.userBG25+'" type=text id=toguserBG25 value="'+Colors.userBG25+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName25 value="'+ Options.userName25 +'"></td></tr>        <TR ><TD width="180" ><INPUT  type=checkbox id=ptEnableUserName11 /> '+culang.mainPlayer+' #11 </td><TD  width="44" ><INPUT style="background:'+Colors.userBG11+'" type=text id=toguserBG11 value="'+Colors.userBG11+'" size=7 maxlength=7></td><TD><input type=text id=togcolorUserName11 value="'+ Options.userName11 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName26 /> '+culang.mainPlayer+' #26 </td><TD ><INPUT style="background:'+Colors.userBG26+'" type=text id=toguserBG26 value="'+Colors.userBG26+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName26 value="'+ Options.userName26 +'"></td></tr>        <TR ><TD ><INPUT  type=checkbox id=ptEnableUserName12 />'+culang.mainPlayer+' #12 </td><TD  ><INPUT style="background:'+Colors.userBG12+'" type=text id=toguserBG12 value="'+Colors.userBG12+'" size=7 maxlength=7></td><TD ><INPUT  type=text id=togcolorUserName12 value="'+ Options.userName12 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName27 /> '+culang.mainPlayer+' #27 </td><TD ><INPUT style="background:'+Colors.userBG27+'" type=text id=toguserBG27 value="'+Colors.userBG27+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName27 value="'+ Options.userName27 +'"></td></tr>        <TR ><TD ><INPUT type=checkbox id=ptEnableUserName13 />'+culang.mainPlayer+' #13 </td><TD ><INPUT style="background:'+Colors.userBG13+'" type=text id=toguserBG13 value="'+Colors.userBG13+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName13 value="'+ Options.userName13 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName28 /> '+culang.mainPlayer+' #28 </td><TD ><INPUT  style="background:'+Colors.userBG28+'" type=text id=toguserBG28 value="'+Colors.userBG28+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName28 value="'+ Options.userName28 +'"></td></tr>        <TR ><TD ><INPUT type=checkbox id=ptEnableUserName14 /> '+culang.mainPlayer+' #14 </td><TD ><INPUT style="background:'+Colors.userBG14+'" type=text id=toguserBG14 value="'+Colors.userBG14+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName14 value="'+ Options.userName14 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName29 /> '+culang.mainPlayer+' #29 </td><TD><INPUT  style="background:'+Colors.userBG29+'" type=text id=toguserBG29 value="'+Colors.userBG29+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName29 value="'+ Options.userName29 +'"></td></tr>        <TR ><TD><INPUT type=checkbox id=ptEnableUserName15 />     '+culang.mainPlayer+' #15  </td><TD ><INPUT style="background:'+Colors.userBG15+'" type=text id=toguserBG15 value="'+Colors.userBG15+'" size=7 maxlength=7></td><TD><INPUT type=text id=togcolorUserName15 value="'+ Options.userName15 +'"></td><TD><INPUT type=checkbox id=ptEnableUserName30 /> '+culang.mainPlayer+' #30 </td><TD ><INPUT style="background:'+Colors.userBG30+'" type=text id=toguserBG30 value="'+Colors.userBG30+'" size=7 maxlength=7></td><TD ><INPUT type=text id=togcolorUserName30 value="'+ Options.userName30 +'"></td></tr>\
                </table>';
                html += '</div></div>';    
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'styleTabOptions\').style.display=(document.getElementById(\'styleTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadStyle+'</a></div>';
                html += '<DIV id="styleTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TD width=2%></td><TD width=66%>'+culang.optionsPopupBorderRadius+' <INPUT type=text id=KspopupBorderRadius size=19 maxlength=19 value="'+ Options.popupBorderRadius +'" /> <sup>(<span class=boldRed>'+culang.optionsPopupBorderRadiusNote+'</span>)</sup></td></tr>\
                <TD width=2%><INPUT id=ptAllowTransparent type=checkbox /></td><TD width=66%>10% '+culang.optionsPopupTransparent+' </td></tr>\
                <TD colspan="2">'+culang.optionsPopupHeight+': <INPUT  type=text id="optHauteurBoite" value="'+ Options.HauteurBoite +'" size=4>'+culang.optionsPopupHeight2+'</td></tr>\
                <TR><TD></td><TD colspan=3><INPUT id=togCustomWideScreenSize type=text size=4 />'+culang.optionsCustomWideScreen+'</td>\
                <TR><TD><INPUT id=boWideOpt type=checkbox '+ (GlobalOptions.pbWideScreen?'CHECKED ':'') +'/></td><TD colspan="3">'+culang.mainWideScreen+': '+ htmlSelector({normal:culang.mainNormal, wide:culang.mainWideScreen, ultra:culang.mainUltra,custom:culang.mainCustom},GlobalOptions.pbWideScreenStyle,'id=KsselectScreenMode') +'</td>\
                <TR><TD width=5%><INPUT id=pbWMapEnable type=checkbox /></td><TD width=27%>'+culang.optionsWideMap+'</td></tr>\
                <TR><TD><INPUT id=MapExtra type=checkbox /></td><TD>'+culang.optionsMapExtras+'</td></tr>\
                <TR><TD><INPUT id=KsLangFlag type=checkbox /></td><TD>'+culang.optionsLangFlagChat+' <img height=16 src="http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/'+LangOptions.culang+'-24x24.png" title="'+culang.KsRunningLanguage+'"></td></tr>\
                <TR><TD><INPUT id=KsHyperlinks type=checkbox /></td><TD>'+culang.optionsHyperlinksChat+'</td></tr>\
                </table>';
                html += '</div>';
            }

            /* avatarTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'avatarTabOptions\').style.display=(document.getElementById(\'avatarTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadAvatars+'</a></div>';
                html += '<DIV id="avatarTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TR><TD><INPUT id=user_icon type=checkbox /></td> <TD>'+culang.optionsChatOwnAvatar+' <INPUT id=togURL3 size=30 type=textbox value="'+Options.URLicon+'" /><input type=button value="'+culang.mainDefault+'" id="KsDefURL3"/> ('+culang.optionsChatOwnAvatar2+')</td></tr></table>\
                <TR><TD><INPUT id=user_iconFlag type=checkbox /></td> <TD>'+culang.optionsChatLangFlag+'</td></tr></table>\
                <div class=pdxStat>'+culang.optionsAvatarHeadMore+'</div>'+culang.optionsAvatarNote+'<HR><font color=#5555CC><b>'+culang.playerSearchPlayerUserID+'</b> <span title="'+culang.optionsUserIDNote+'">'+parseInt([Seed.tutorial.userId])+'</span><BR>'+culang.optionsAvatarForm+'';
                html += '</div>';
            }
            // <img src="'+Options.URLicon+'">
            
            /* reportTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'reportTabOptions\').style.display=(document.getElementById(\'reportTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadReports+'</a></div>';
                html += '<DIV id="reportTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TR><TD><INPUT id=togRptGift type=checkbox /></td><TD>'+culang.optionsReportsDelInboxGifts+'</td></tr>\
                <TR><TD><INPUT id=togAllRpts type=checkbox /></td><TD>'+culang.optionsReportsExtras+'</td></tr>\
                <TR><TD><INPUT id=togAllMembers type=checkbox /></td><TD>'+culang.optionsReportsViewMember+'</td></tr>\
                <TR><TD><INPUT id=togAtkDelete type=checkbox DISABLED/></td><TD>'+culang.optionsReportsDeleteButton+'</td></tr>\
                <TR><TD></td><td>'+culang.optionsReportsAutoDelete+' <input type=button id=bodeletenow value="'+culang.mainDeleteNow+'">'+
                ' (<INPUT id=DeleteReportDebug type=checkbox '+(DeleteReports.trace?'CHECKED':'')+'/>Debug)'+'</tr>\
                <TR><td></td><TD colspan=1><INPUT id=delete4toggle type=checkbox />'+culang.optionsReportsAutoDeleteScout+' <br><INPUT id=deletetoggle type=checkbox /> '+culang.optionsReportsAutoDeleteBarbTrans+'&nbsp;<br><INPUT id=deletes0toggle type=checkbox /> '+culang.optionsReportsAutoDeleteTransport+'<br><INPUT id=deletes1toggle type=checkbox />'+culang.mainWildernes+'<br><INPUT id=deletes2toggle type=checkbox />'+unsafeWindow.g_js_strings.commonstr.darkForest+'&nbsp;<br><INPUT id=deletes3toggle type=checkbox /> '+culang.mainReinforce+'<br><INPUT id=deletes5toggle type=checkbox /> '+culang.mainAttack+'<br><INPUT id=deletes6toggle type=checkbox /> '+culang.optionsReportsAutoDeleteCrestCity+'</td></tr>\
                <TR><TD></td><td> '+culang.mainIntervall+': <input type=text size=3 id=Ksdeletetimer value="' + Options.DeleteTimerMinute + '"> '+culang.mainMinutes+' </td></tr></table>';
                html += '</div>';
            }

            /* soundsTabOptions */
            if(true){
                html += '<DIV class=pdxStat><span title="'+culang.optionsHeadSoundsNote+'" ><a href="#" onclick="document.getElementById(\'soundsTabOptions\').style.display=(document.getElementById(\'soundsTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadSounds+'</a></div>';
                html += '<DIV id="soundsTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TR><TD colspan=2>'+culang.optionsSoundsLinks+'</td></tr>\
                <TR><TD><INPUT id=togWhisperOn type=checkbox /></td><TD>'+culang.optionsChatWhisperSound+' <INPUT id=togURL1 size=40 type=textbox value="'+ Options.URLson1 +'" /> '+culang.optionsChatSoundVolume+' <INPUT id=togURLson1Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson1Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL1"></td></tr>\
                <TR><TD><INPUT id=togEclaireurOn type=checkbox /></td><TD>'+culang.optionsChatScoutSound+' <INPUT id=togURL4 size=40 type=textbox value="'+ Options.URLson4 +'" /> '+culang.optionsChatSoundVolume+' <INPUT id=togURLson4Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson4Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL4"></input></td></tr>\
                <TR><TD><INPUT id=togAttaqueOn type=checkbox /></td><TD>'+culang.optionsChatAttackSound+' <INPUT id=togURL2 size=40 type=textbox value="'+ Options.URLson2 +'" /> '+culang.optionsChatSoundVolume+' <INPUT id=togURLson2Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson2Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL2"></input></td></tr>\
                <TR><TD><INPUT id=togWildSoundOn type=checkbox /></td><TD>'+culang.optionsChatWildSound+' <INPUT id=togURL5 size=40 type=textbox value="'+ Options.URLson5 +'" /> '+culang.optionsChatSoundVolume+' <INPUT id=togURLson5Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson5Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL5"></input></td></tr>\
                <TR><TD><INPUT id=togFoodSoundOn type=checkbox /></td><TD>'+culang.optionsChatFoodSound+' <INPUT id=togURL6 size=40 type=textbox value="'+ Options.URLson6 +'" /> '+culang.optionsChatSoundVolume+' <INPUT id=togURLson6Vol size=3 maxlength=3 type=textbox value="'+ Options.URLson6Vol +'" /> - <input type=button value="'+culang.mainDefault+'" id="KsDefURL6"></input></td></tr>\
                <TR><TD><INPUT id=togKsFunSoundAttack type=checkbox /></td><TD>'+culang.optionsSoundFunChatCommands+' '+culang.optionsSoundGetFSAttack+' - '+culang.optionsSoundFunSoundURL+' <INPUT id=togURLF1 size=15 type=textbox value="'+ Options.soundURLF1 +'" /> '+culang.mainVolume+' <INPUT id=togURLF1vol size=3 type=textbox value="'+ Options.URLsonF1vol +'" /> <input type=button value="'+culang.mainDefault+'" id="PDXDefURLF1"> </td></tr>\
                <TR><TD><INPUT id=togKsFunSoundHorn type=checkbox /></td><TD>'+culang.optionsSoundFunChatCommands+' '+culang.optionsSoundGetFSHorn+' - '+culang.optionsSoundFunSoundURL+' <INPUT id=togURLF2 size=15 type=textbox value="'+ Options.soundURLF2 +'" /> '+culang.mainVolume+' <INPUT id=togURLF2vol size=3 type=textbox value="'+ Options.URLsonF2vol +'" /> <input type=button value="'+culang.mainDefault+'" id="PDXDefURLF2"> </td></tr>\
                <TR><TD><INPUT id=togKsFunSoundGun type=checkbox /></td><TD>'+culang.optionsSoundFunChatCommands+''+culang.optionsSoundGetFSGun+' - '+culang.optionsSoundFunSoundURL+' <INPUT id=togURLF3 size=15 type=textbox value="'+ Options.soundURLF3 +'" /> '+culang.mainVolume+' <INPUT id=togURLF3vol size=3 type=textbox value="'+ Options.URLsonF3vol +'" /> <input type=button value="'+culang.mainDefault+'" id="PDXDefURLF3"> </td></tr></table>';
                html += '</div>';
            }

            /* towerTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'towerTabOptions\').style.display=(document.getElementById(\'towerTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadTower+'</a></div>';
                html += '<DIV id="towerTabOptions" style="display:none;">';
                html +='<TABLE class=pdxTab>\
                <TR><TD><INPUT id=pcalertEnable type=checkbox '+ (Options.alertConfig.aChat?'CHECKED ':'') +'/></td><TD>'+culang.optionsTowerEnable+' </td></tr>\
                <TR><TD><INPUT id=boSoundEnable type=checkbox '+ (Options.alertSound.enabled?'CHECKED ':'') +'/></td><TD>'+culang.optionsTowerEnableSounds+'</td></tr>\
                <TR><TD></td><TD><DIV id=boLoadingSwf>'+culang.optionsChargement+'</div><DIV style="display:none" id=boSoundOpts><TABLE cellpadding=0 cellspacing=0>\
                <TR><TD align=right>'+culang.optionsSoundURL+': &nbsp; </td><TD><INPUT id=bosoundFile type=text size=55 maxlength=160 value="'+ Options.alertSound.soundUrl +'" \ title="'+culang.optionsSoundURLNote+'"></td><TD><INPUT id=boSoundLoad type=submit value="'+culang.buttonDownload+'"><INPUT id=boSoundDefault type=submit value="'+culang.mainDefault+'"></td></tr>\
                <TR><TD align=right>'+culang.mainVolume+': &nbsp; </td><TD><TABLE cellpadding=0 cellspacing=0 class=pdxTab><TR valign=middle><TD><SPAN id=boVolSlider></span></td><TD width=15></td><TD align=right id=boVolOut>0</td></td></table></td><TD align=center><SPAN id=optionsLoadSWF>xx</span></td></tr>\
                <TR><TD align=right><INPUT id=boSoundRepeat type=checkbox '+ (Options.alertSound.repeat?'CHECKED ':'') +'/></td><TD> '+culang.mainRepeat+' <INPUT id=boSoundEvery type=text size=2 maxlength=5 value="'+ Options.alertSound.repeatDelay +'"> '+culang.mainMinutes+'</td></tr>\
                <TR><TD></td><TD>'+culang.optionsSoundAlertLenght+' <INPUT id=boSoundLength type=text size=3 maxlength=5 value="'+ Options.alertSound.playLength +'"> '+culang.mainSeconds+'</td></tr>\
                <TR><TD></td><TD><INPUT type=submit value="'+culang.buttonPlaySound+'" id=boPlayNow> &nbsp; <INPUT id=optionsSoundStop type=submit value="'+culang.buttonStopSound+'"></td></tr></table></div></td></tr><TR><TD></td><TD>';
                html +='<TABLE cellpadding=0 cellspacing=0 class=pdxTab><TR><TD align=right>'+culang.optionsTowerPostSettings+'  : </td><TD>&nbsp;<INPUT id=pcalertSendToAlly type=checkbox '+ (Options.alertConfig.sendtoAlly?'CHECKED ':'') +' /> '+culang.optionsTowerPostSettings2+' <INPUT id=pcalertSendAsWhisper type=checkbox '+ (Options.alertConfig.sendasWhisper?'CHECKED ':'') +' /> '+culang.optionsTowerPostSettings3+' </td></tr>\
                <TR><TD align=right>'+culang.optionsTowerOwnMessage+' &nbsp; </td><TD><INPUT id=pcalertPrefix type=text size=55 maxlength=120 value="'+ Options.alertConfig.aPrefix +'" \></td></tr>\
                <TR><TD align=right>'+culang.optionsTowerAlertIf+' &nbsp; </td><TD><INPUT id=pcalertWild type=checkbox '+ (Options.alertConfig.wilds?'CHECKED ':'') +'/> '+culang.optionsTowerAlertIfWild+'  <INPUT id=pcalertScout type=checkbox '+ (Options.alertConfig.scouting?'CHECKED ':'') +'/> '+culang.optionsTowerAlertIfScout+' </td></tr>\
                <TR><TD align=right>'+culang.optionsTowerMinTroops+' :<br></td><TD><INPUT id=pcalertTroops type=text size=7 value="'+ Options.alertConfig.minTroops +'" \> '+culang.optionsTowerMinTroops2+' <INPUT id=pcalertTroops2 type=text size=7 value="'+ Options.alertConfig.minTroops2 +'" \> '+culang.optionsTowerMinTroops3+' &nbsp; &nbsp; <span id=pcalerterr></span></td></tr>\
                <TR><TD align=right>'+culang.mainDefense+': &nbsp; </td><TD><INPUT id=pbalertDefend type=checkbox '+ (Options.alertConfig.defence?'CHECKED ':'') +' \> &nbsp; &nbsp; </td></tr>\
                <TR><TD align=right>'+culang.optionsTowerFletch+' &nbsp; </td><TD><INPUT id=pcalertFletching type=checkbox '+ (Options.alertConfig.fletching?'CHECKED ':'') +'/></td></tr>\
                <TR><TD align=right>'+culang.optionsTowerThrone+' </td><TD><INPUT id=pcalertTroneRange type=checkbox '+ (Options.alertConfig.TroneRange?'CHECKED ':'') +'/> '+culang.optionsTowerRange+'  <INPUT id=pcalertTroneRangeDebuff type=checkbox '+ (Options.alertConfig.TroneRangeDebuff?'CHECKED ':'') +'/> '+culang.optionsTowerRangeDebuff+' </td></tr>\
                <TR><TD align=right>'+culang.mainKnights+' ('+culang.mainWithoutBosster+'): &nbsp; </td><TD><INPUT id=pcalertMarechal type=checkbox '+ (Options.alertConfig.marechal?'CHECKED ':'') +'/></td></tr>\
                <TR><TD align=right>'+culang.optionsTowerDefBooster+' &nbsp; </td><TD><INPUT id=pcalertdefBoost type=checkbox '+ (Options.alertConfig.defBoost?'CHECKED ':'') +'/></td></tr>\
                <TR><TD align=right>'+culang.mainEmbassy+': &nbsp; </td><TD><INPUT id=pcalertEmbassy type=checkbox '+ (Options.alertConfig.embassy?'CHECKED ':'') +'/></td></tr>\
                <TR><TD align=right>'+culang.mainDefense+': &nbsp; </td><TD><INPUT id=pcalertMytroops type=checkbox '+ (Options.alertConfig.mytroops?'CHECKED ':'') +'/>'+culang.mainTroops+' <INPUT id=pcalertDefense type=checkbox '+ (Options.alertConfig.defense?'CHECKED ':'') +' /> '+culang.mainWall+' </td></tr>\
                <TR><TD align=right>'+culang.optionsTowerFoodLeft+': &nbsp; </td><TD><INPUT id=pcalertFood type=checkbox '+ (Options.alertConfig.food?'CHECKED ':'') +' /></td></tr>\
                <TR><TD align=right>'+culang.optionsTowerHideHQ+':</td><td><INPUT id=pcalertQG type=checkbox '+ (Options.alertConfig.MonQG?'CHECKED ':'') +' /></td></tr>\
                <TR><TD align=right>'+culang.optionsTowerStopOnAttack+':</td><td><INPUT id=Ksalertraid type=checkbox '+ (Options.alertConfig.raid?'CHECKED':'') +'/> '+culang.optionsTowerStopOnAttackRaid+'  <INPUT id=Ksalertappro type=checkbox '+ (Options.alertConfig.appro?'CHECKED':'') +'/> '+culang.optionsTowerStopOnAttackSupply+'  <INPUT id=Ksalertautofo type=checkbox '+ (Options.alertConfig.autofo?'CHECKED':'') +'/> '+culang.optionsTowerStopOnAttackDarkForest+' <INPUT id=Ksalertautots type=checkbox '+ (Options.alertConfig.autots?'CHECKED':'') +'/> '+culang.optionsTowerStopOnAttackCrest+' </td></tr>\
                <TR><TD align=right>' + culang.mainChangeThroneSet + ':</td><td><INPUT id=Ksalertthrone type=checkbox '+ (Options.alertConfig.changeThrone?'CHECKED':'') +'/> ' + culang.mainToThroneSet + ': <SELECT id=KsalertTSet>'; //15.10.2012 Bommel
                for (i=1;i<=Seed.throne.slotNum;i++){
                    html += '<option value="'+i+'">'+i+'</option>';
                }
                html +='</select> ' + culang.mainWhenAttacked + '</td>\
                <TR><TD align=right>' + culang.mainResetThrone + ':</td><td><INPUT id=KsalertthroneRet type=checkbox '+ (Options.alertConfig.returnThrone?'CHECKED':'') +'/> ' + culang.mainToThroneSet + ': <SELECT id=KsalertTSetRet>'; //16.10.2012 Bommel
                for (i=1;i<=Seed.throne.slotNum;i++){
                    html += '<option value="'+i+'">'+i+'</option>';
                }
                html +='</select> ' + culang.mainIf + ' <input type="text" id=KsalertthroneMin style="text-align:center;" size=3 maxlength=5 value="'+Options.alertConfig.returnThroneMin+'"> ' + culang.mainMinutesNoAttack + '</td>\
                </tr>\
                <TR style="display:none"><TD align=right>'+culang.optionsTowerEMail+':</td><TD><INPUT id=pcalertSendEmail type=checkbox '+ (Options.alertConfig.sendEmail?'CHECKED ':'') +' /><INPUT id=pcalertEmailAddress type=text size=36 value="'+ Options.alertConfig.emailAddress +'" \> &nbsp; &nbsp;</td></tr>\
                <TR style="display:none"><TD align=right>'+culang.optionsTowerEMailToken+': &nbsp; </td><TD><INPUT id=pcalertToken type=text size=36 value="'+ Options.alertConfig.token +'" \> &nbsp; &nbsp;</td></tr></table></table>'; //16.10.2012 Bommel
                html += '</div>';
            }
            
            /* moreTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'moreTabOptions\').style.display=(document.getElementById(\'moreTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadMore+'</a></div>';
                html += '<DIV id="moreTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>';
                var citySelect = '<SELECT id=pcalertHQ name=pcalertHQ><option value="">-- '+culang.mainSelect+' --</option>';
                var couleur="";
                for (var c=0; c<Cities.numCities; c++) {
                    aCity = Cities.cities[c].id;
                    aVisuCity = Cities.cities[c].name + ' '+Cities.cities[c].x + ','+ Cities.cities[c].y+' ';
                    citySelect += '<option value=\''+ aCity +'\' '+ (Options.alertConfig.hq==aCity?'SELECTED ':'') +'>'+aVisuCity+'</option>';
                }
                citySelect += '</select>';
                html +='<TR><td></td><TD align=left>'+culang.optionsMoreSelectHQ+':&nbsp;'+ citySelect +'</td></tr>\
                <TR><TD><INPUT id=togSelQG type=checkbox /></td><TD>'+culang.optionsMoreOpenHQ+' </td></tr>\
                <TR><TD><INPUT id=pbGoldEnable type=checkbox /></td><TD>'+culang.optionsMoreAutoGold+' <INPUT id=pbgoldLimit type=text size=2 maxlength=3>'+culang.optionsMoreAutoGold2+'</td></tr>\
                <TR><TD><INPUT id=togAttackPicker type=checkbox /></td><TD>'+culang.optionsMoreCityButtons+' ('+culang.optionsMoreCityButtons2+')  </td></tr>\
                <TR><TD><INPUT id=togEnhanceMsging type=checkbox /></td><TD>'+culang.optionsMoreMessage+'</td></tr></table>';
                html += '</div>';
            }

            /* bugFixesTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'bugFixesTabOptions\').style.display=(document.getElementById(\'bugFixesTabOptions\').style.display== \'block\')?\'none\':\'block\';">'+culang.optionsHeadBugFixes+'</a></div>';
                html += '<DIV id="bugFixesTabOptions" style="display:none;">';
                html += '<TABLE class=pdxTab>\
                <TR><TD><INPUT id=togKnightSelect type=checkbox /></td><TD>'+culang.optionsBugDisableKnightSel+'  ('+culang.optionsBugDisableKnightSel2+')</td></tr>\
                <TR><TD><INPUT id=togCoordBox type=checkbox /></td><TD>'+culang.optionsBugCoordBox+'</td></tr>\
                <TR><TD><INPUT id=togMightKoCBugFix type=checkbox /></td><TD>'+culang.optionsBugMightFix+'</td></tr>\
                <TR><TD><INPUT id=togResKoCBugFix type=checkbox /></td><TD>'+culang.optionsBugResFix+'</td></tr>\
                <TR style="display:none;"><TD><INPUT id=togMapDistFix type=checkbox /></td><TD>'+culang.optionsBugMapDistance+'</td></tr></table>';
                html += '</div>';
            }

            /* resetTabOptions */
            if(true){
                html += '<DIV class=pdxStat><a href="#" onclick="document.getElementById(\'resetTabOptions\').style.display=(document.getElementById(\'resetTabOptions\').style.display== \'block\')?\'none\':\'block\';" title="'+culang.optionsHeadResetNote+'">'+culang.optionsHeadReset+'</a></div>';
                html += '<DIV id="resetTabOptions" style="display:none;">';
                html +='<TABLE class=pdxTab>\
                <TR><TD>'+strButton20(''+culang.buttonResetOptions+'', 'id=KsResetALL')+'</td><TD>'+strButton20(''+culang.buttonResetColors+'', 'id=ResetALL')+'</td></tr>\
                </table>';
                html += '</div>';
            }
            html +="</div>";

            t.cont.innerHTML = html;
            
            t.togOpt ('togRptGift', 'enhancedinbox', DispReport.setEnable, DispReport.isDispReportAvailable);

        // if (Options.pdxLangFlag) { document.getElementById('pdxLangFlag').innerHTML = '<img height=24 width=24 src="http://koc-power-pdx.googlecode.com/svn/release/old/139/img/langflags/'+LangOptions.culang+'-24x24.png" title="Du Benutz zur Zeit die Deutsche version vergiss nicht das Spiel selbst auch auf die gleiche Sprache einszustellen!">'; }

            ById('EmoHelp').addEventListener('click', function(){t.EmoHelp();} , false);
            // ById('boaideoptions').addEventListener('click', function(){
            // window.open(homePage+" ");
            // } , false);

            ById('DeleteReportDebug').addEventListener('click', function(){ 
                DeleteReports.trace=ById('DeleteReportDebug').checked;
            }, false);
            
            ById('bodeletenow').addEventListener('click', function(){ DeleteReports.startdeletereports(); }, false);
            t.togOpt ('togAtkDelete', 'reportDeleteButton');
            t.togOpt ('KsNewTab', 'NewTab');
            t.togOpt ('KsIdHomeTab', 'KsHomeTab');

            ById('KsNewTabURL').addEventListener ('change', function () {
                Options.NewTabURL = ById('KsNewTabURL').value;
                saveOptions();
            }, false);
            ById('KsNewTabName').addEventListener ('change', function () {
                Options.NewTabName = ById('KsNewTabName').value;
                saveOptions();
            }, false);

            ById('togChatLeaders').addEventListener('change', function(){
                Colors.ChatLeaders = ById('togChatLeaders').value;
                ById('togChatLeaders').style.backgroundColor=ById('togChatLeaders').value;
            }, false);
            ById('togMainTitle').addEventListener('change', function(){
                Colors.MainTitle = ById('togMainTitle').value;
                ById('togMainTitle').style.backgroundColor=ById('togMainTitle').value;
            }, false);
            ById('togMainTitleHover').addEventListener('change', function(){
                Colors.MainTitleHover = ById('togMainTitleHover').value;
                ById('togMainTitleHover').style.backgroundColor=ById('togMainTitleHover').value;
            }, false);
            ById('togMainTitleBackground').addEventListener('change', function(){
                Colors.MainTitleBackground = ById('togMainTitleBackground').value;
                ById('togMainTitleBackground').style.backgroundColor=ById('togMainTitleBackground').value;
            }, false);
            ById('togMainTitle2').addEventListener('change', function(){
                Colors.MainTitle2 = ById('togMainTitle2').value;
                ById('togMainTitle2').style.backgroundColor=ById('togMainTitle2').value;
            }, false);
            ById('togMainTitle2Hover').addEventListener('change', function(){
                Colors.MainTitle2Hover = ById('togMainTitle2Hover').value;
                ById('togMainTitle2Hover').style.backgroundColor=ById('togMainTitle2Hover').value;
            }, false);
            ById('togMainTitle2Background').addEventListener('change', function(){
                Colors.MainTitle2Background = ById('togMainTitle2Background').value;
                ById('togMainTitle2Background').style.backgroundColor=ById('togMainTitle2Background').value;
            }, false);
            ById('togChatVC').addEventListener('change', function(){
                Colors.ChatVC = ById('togChatVC').value;
                ById('togChatVC').style.backgroundColor=ById('togChatVC').value;
            }, false);
            ById('togChatC').addEventListener('change', function(){
                Colors.ChatChancy = ById('togChatC').value;
                ById('togChatC').style.backgroundColor=ById('togChatC').value;
            }, false);
            ById('togChatAtt').addEventListener('change', function(){
                Colors.ChatAtt = ById('togChatAtt').value;
                ById('togChatAtt').style.backgroundColor=ById('togChatAtt').value;
            }, false);
            ById('togChatAttFont').addEventListener('change', function(){
                Colors.ChatAttFont = ById('togChatAttFont').value;
                ById('togChatAttFont').style.backgroundColor=ById('togChatAttFont').value;
            }, false);
            ById('togChatWildAtt').addEventListener('change', function(){
                Colors.ChatWildAtt = ById('togChatWildAtt').value;
                ById('togChatWildAtt').style.backgroundColor=ById('togChatWildAtt').value;
            }, false);
            ById('togChatWildAttFont').addEventListener('change', function(){
                Colors.ChatWildAttFont = ById('togChatWildAttFont').value;
                ById('togChatWildAttFont').style.backgroundColor=ById('togChatWildAttFont').value;
            }, false);
            ById('togChatLowFood').addEventListener('change', function(){
                Colors.ChatLowFood = ById('togChatLowFood').value;
                ById('togChatLowFood').style.backgroundColor=ById('togChatLowFood').value;
            }, false);
            ById('togChatLowFoodFont').addEventListener('change', function(){
                Colors.ChatLowFoodFont = ById('togChatLowFoodFont').value;
                ById('togChatLowFoodFont').style.backgroundColor=ById('togChatLowFoodFont').value;
            }, false);
            ById('togChatScoutAlert').addEventListener('change', function(){
                Colors.ChatEcl = ById('togChatScoutAlert').value;
                ById('togChatScoutAlert').style.backgroundColor=ById('togChatScoutAlert').value;
            }, false);
            ById('togChatScoutAlertFont').addEventListener('change', function(){
                Colors.ChatEclFont = ById('togChatScoutAlertFont').value;
                ById('togChatScoutAlertFont').style.backgroundColor=ById('togChatScoutAlertFont').value;
            }, false);
            ById('togChatGlo').addEventListener('change', function(){
                Colors.ChatGlo = ById('togChatGlo').value;
                ById('togChatGlo').style.backgroundColor=ById('togChatGlo').value;
            }, false);
            ById('togChatGloFont').addEventListener('change', function(){
                Colors.ChatGloFont = ById('togChatGloFont').value;
                ById('togChatGloFont').style.backgroundColor=ById('togChatGloFont').value;
            }, false);
            ById('togChatAlliance').addEventListener('change', function(){
                Colors.ChatAlliance = ById('togChatAlliance').value;
                ById('togChatAlliance').style.backgroundColor=ById('togChatAlliance').value;
            }, false);
            ById('togChatAllianceFont').addEventListener('change', function(){
                Colors.ChatAllianceFont = ById('togChatAllianceFont').value;
                ById('togChatAllianceFont').style.backgroundColor=ById('togChatAllianceFont').value;
            }, false);
            if (couleur!="") {
                ById('pcalertHQ').style.background="red";
            }

            ById('boWideOpt').addEventListener ('change', t.e_wideChanged, false);

            ById('togEnableBrowserBG').addEventListener ('change', function(){
                GlobalOptions.enableBrowserBG = ById('togEnableBrowserBG').checked;
                GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
            },false);
            ById('pbsendmeaway').addEventListener ('click', function(){
                GlobalOptions.pbNoMoreKabam = document.getElementById('pbsendmeaway').checked;
                GM_setValue ('Options_??', JSON2.stringify(GlobalOptions));
            },false);

            ById('KsWatchEnable').addEventListener ('change', t.e_watchChanged, false);
            ById('selectprivacymode').addEventListener ('change', function(){
                GlobalOptions.autoPublishPrivacySetting = ById('selectprivacymode').value;
                GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
            },false);

            ById('PubReq').addEventListener ('change', function(){
                GlobalOptions.autoPublishGamePopups = ById('PubReq').checked;
                GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
            },false);

            ById('KsResetALL').addEventListener ('click', function(){
                var serverID = getServerId();
                RemoveList = (GM_listValues());
                for (i=0;i<RemoveList.length;i++){
                    GM_deleteValue(RemoveList[i]);
                }
                ResetAll=true;
                reloadKOC();
            },false);

            ById('ResetALL').addEventListener ('click', function(){
                RemoveList = (GM_listValues());
                for (i=0;i<RemoveList.length;i++){
                    if (RemoveList[i] == "Colors") GM_deleteValue(RemoveList[i]);
                }
                ResetColors=true;
                reloadKOC();
            },false);

            ById('togResetStyleOpt').addEventListener ('click', function(){
                var serverID = getServerId();
                RemoveList = (GM_listValues());
                for (i=0;i<RemoveList.length;i++){

                    if (RemoveList[i] == "TabOptions_"+serverID) GM_deleteValue(RemoveList[i]);
                }
                ResetTabOptions=true;
                reloadKOC();
            },false);
            ById('optFoodChatHours').addEventListener ('change', function () {
                var x = ById('optFoodChatHours').value;
                if (isNaN(x) || x<0.01 || x>99999){
                    ById('optFoodChatHours').value = Options.foodChatWarnHours;
                    return;
                }
                Options.foodChatWarnHours = x;
                saveOptions();
            }, false);
            /*
            ById('pbupdatelanglist').addEventListener ('click', function () {
                GM_xmlhttpRequest({
                    method: 'GET',
                    url: ''+KsLangpackFolder+'',
                    headers: {
                        'Accept': 'text/javascript',
                    },
                    onload: function(responseDetails) {
                        var exp = /(\w\w)(?=.js<\/a>)/gim;
                        var str = responseDetails.responseText;
                        var str = str.match(exp);
                        for (i in str) {
                            if (str.length > i) {
                                if(str[i]=="SR") continue;// exclude string resource file
                                LangOptions.langpacks[str[i]] = true;
                            };
                        }
                        saveLangOptions();
                    }
                });
            }, false);
            */
            ById('pbLang').addEventListener ('change', function () {
                LangOptions.culang = this.options[this.selectedIndex].text ;
                saveLangOptions();
            }, false);
            ById('KsselectScreenMode').addEventListener ('change', function(){
                GlobalOptions.pbWideScreenStyle = ById('KsselectScreenMode').value;
                GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
            },false);
            ById('KsBackgroundColor').addEventListener ('change', function(){
                GlobalOptions.bgCol = ById('KsBackgroundColor').value;
                GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
                ById('KsBackgroundColor').style.backgroundColor=ById('KsBackgroundColor').value;
            },false);
            ById('KsBackgroundImage').addEventListener ('change', function(){
                GlobalOptions.bgImg = ById('KsBackgroundImage').value;
                GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
            },false);
            ById('KsBackSelector').addEventListener ('change', function(){
                GlobalOptions.backStyle = ById('KsBackSelector').value;
                GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
            },false);
            ById('KsUpdateChatNoteSel').addEventListener ('change', function(){
                GlobalOptions.updateChatNote = ById('KsUpdateChatNoteSel').value;
                GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
            },false);

            t.mss = new CmatSimpleSound("http://kofc.god-like.info/power/swf/alarmplayer.swf", null, {height:0, width:0}, t.e_swfLoaded, 'debug=n');
            t.mss.swfDebug = function (m){ logit ('SWF: '+ m)};
            t.mss.swfPlayComplete = t.e_soundFinished;
            t.mss.swfLoadComplete = t.e_soundFileLoaded;
            unsafeWindow.matSimpleSound01 = t.mss;

            t.volSlider = new SliderBar (ById('boVolSlider'), 200, 21, 0);
            t.volSlider.setChangeListener(t.e_volChanged);
            ById('boPlayNow').addEventListener ('click', function (){t.playSound(false)}, false);
            ById('optionsSoundStop').addEventListener ('click', t.stopSoundAlerts, false);

            ById('boSoundRepeat').addEventListener ('change', function (e){Options.alertSound.repeat = e.target.checked}, false);
            ById('boSoundEvery').addEventListener ('change', function (e){Options.alertSound.repeatDelay = e.target.value}, false);
            ById('boSoundLength').addEventListener ('change', function (e){Options.alertSound.playLength = e.target.value}, false);
            ById('boSoundEnable').addEventListener ('change', function (e){Options.alertSound.enabled = e.target.checked}, false);

            ById('optionsSoundStop').disabled = true;
            ById('bosoundFile').addEventListener ('change', function (){
                Options.alertSound.soundUrl = ById('bosoundFile').value;
                t.loadUrl (Options.alertSound.soundUrl);
            }, false);
            ById('boSoundDefault').addEventListener ('click', function (){
                ById('bosoundFile').value = DEFAULT_ALERT_SOUND_URL;
                Options.alertSound.soundUrl = DEFAULT_ALERT_SOUND_URL;
                t.loadUrl (DEFAULT_ALERT_SOUND_URL);
            }, false);
            t.togOpt ('KsLangFlag', 'pdxLangFlag');
            t.togOpt ('KsHyperlinks', 'pdxHyperlinks');
            t.togOpt ('KsgmtClock', 'gmtClock', gmtClock.setEnable);
            t.togOpt ('DelRules', 'ChatRules');
            t.togOpt ('togSelQG', 'SelQG');
            t.togOpt ('KsSmiley', 'Smiley');
            t.togOpt ('togDeleteButtons', 'deleteButtons');
            t.togOpt ('togmerlinClose', 'merlinClose');
            t.togOpt ('KsChatLeader', 'ChatLearder');
            t.togOpt ('togPDXMenuLeft', 'pdxMenuLeft');
            t.togOpt ('togPostMultiUpdate', 'postMultiUpdate');
            t.togOpt ('togShowMultiUpdateNote', 'showMultiUpdateNote');
            t.togOpt ('pbGoldEnable', 'pbGoldEnable', CollectGold.setEnable);
            t.changeOpt ('pbgoldLimit', 'pbGoldHappy');
            t.changeOpt ('togcolorUserName1', 'userName1'); t.changeOpt ('togcolorUserName2', 'userName2'); t.changeOpt ('togcolorUserName3', 'userName3'); t.changeOpt ('togcolorUserName4', 'userName4'); t.changeOpt ('togcolorUserName5', 'userName5'); t.changeOpt ('togcolorUserName6', 'userName6'); t.changeOpt ('togcolorUserName7', 'userName7'); t.changeOpt ('togcolorUserName8', 'userName8'); t.changeOpt ('togcolorUserName9', 'userName9'); t.changeOpt ('togcolorUserName10', 'userName10'); t.changeOpt ('togcolorUserName11', 'userName11'); t.changeOpt ('togcolorUserName12', 'userName12'); t.changeOpt ('togcolorUserName13', 'userName13'); t.changeOpt ('togcolorUserName14', 'userName14'); t.changeOpt ('togcolorUserName15', 'userName15'); t.changeOpt ('togcolorUserName16', 'userName16'); t.changeOpt ('togcolorUserName17', 'userName17'); t.changeOpt ('togcolorUserName18', 'userName18'); t.changeOpt ('togcolorUserName19', 'userName19'); t.changeOpt ('togcolorUserName20', 'userName20'); t.changeOpt ('togcolorUserName21', 'userName21'); t.changeOpt ('togcolorUserName22', 'userName22'); t.changeOpt ('togcolorUserName23', 'userName23'); t.changeOpt ('togcolorUserName24', 'userName24'); t.changeOpt ('togcolorUserName25', 'userName25'); t.changeOpt ('togcolorUserName26', 'userName26'); t.changeOpt ('togcolorUserName27', 'userName27'); t.changeOpt ('togcolorUserName28', 'userName28'); t.changeOpt ('togcolorUserName29', 'userName29');    t.changeOpt ('togcolorUserName30', 'userName30');
            t.togOpt ('ptEnableUserName1', 'enableUserName1'); t.togOpt ('ptEnableUserName2', 'enableUserName2'); t.togOpt ('ptEnableUserName3', 'enableUserName3'); t.togOpt ('ptEnableUserName4', 'enableUserName4'); t.togOpt ('ptEnableUserName5', 'enableUserName5'); t.togOpt ('ptEnableUserName6', 'enableUserName6'); t.togOpt ('ptEnableUserName7', 'enableUserName7'); t.togOpt ('ptEnableUserName8', 'enableUserName8'); t.togOpt ('ptEnableUserName9', 'enableUserName9'); t.togOpt ('ptEnableUserName10', 'enableUserName10');    t.togOpt ('ptEnableUserName11', 'enableUserName11'); t.togOpt ('ptEnableUserName12', 'enableUserName12'); t.togOpt ('ptEnableUserName13', 'enableUserName13'); t.togOpt ('ptEnableUserName14', 'enableUserName14'); t.togOpt ('ptEnableUserName15', 'enableUserName15'); t.togOpt ('ptEnableUserName16', 'enableUserName16'); t.togOpt ('ptEnableUserName17', 'enableUserName17'); t.togOpt ('ptEnableUserName18', 'enableUserName18'); t.togOpt ('ptEnableUserName19', 'enableUserName19'); t.togOpt ('ptEnableUserName20', 'enableUserName20'); t.togOpt ('ptEnableUserName21', 'enableUserName21'); t.togOpt ('ptEnableUserName22', 'enableUserName22'); t.togOpt ('ptEnableUserName23', 'enableUserName23'); t.togOpt ('ptEnableUserName24', 'enableUserName24'); t.togOpt ('ptEnableUserName25', 'enableUserName25'); t.togOpt ('ptEnableUserName26', 'enableUserName26'); t.togOpt ('ptEnableUserName27', 'enableUserName27'); t.togOpt ('ptEnableUserName28', 'enableUserName28'); t.togOpt ('ptEnableUserName29', 'enableUserName29'); t.togOpt ('ptEnableUserName30', 'enableUserName30');
            t.changeColors ('toguserBG1', 'userBG1'); t.changeColors ('toguserBG2', 'userBG2'); t.changeColors ('toguserBG3', 'userBG3'); t.changeColors ('toguserBG4', 'userBG4'); t.changeColors ('toguserBG5', 'userBG5'); t.changeColors ('toguserBG6', 'userBG6'); t.changeColors ('toguserBG7', 'userBG7'); t.changeColors ('toguserBG8', 'userBG8'); t.changeColors ('toguserBG9', 'userBG9'); t.changeColors ('toguserBG10', 'userBG10'); t.changeColors ('toguserBG11', 'userBG11'); t.changeColors ('toguserBG12', 'userBG12'); t.changeColors ('toguserBG13', 'userBG13'); t.changeColors ('toguserBG14', 'userBG14'); t.changeColors ('toguserBG15', 'userBG15'); t.changeColors ('toguserBG16', 'userBG16'); t.changeColors ('toguserBG17', 'userBG17'); t.changeColors ('toguserBG18', 'userBG18'); t.changeColors ('toguserBG19', 'userBG19'); t.changeColors ('toguserBG20', 'userBG20'); t.changeColors ('toguserBG21', 'userBG21'); t.changeColors ('toguserBG22', 'userBG22'); t.changeColors ('toguserBG23', 'userBG23'); t.changeColors ('toguserBG24', 'userBG24'); t.changeColors ('toguserBG25', 'userBG25'); t.changeColors ('toguserBG26', 'userBG26'); t.changeColors ('toguserBG27', 'userBG27'); t.changeColors ('toguserBG28', 'userBG28'); t.changeColors ('toguserBG29', 'userBG29');    t.changeColors ('toguserBG30', 'userBG30');    
            t.togOpt ('togKsFunSoundAttack', 'KsFunSoundAttack');    t.togOpt ('togKsFunSoundHorn', 'KsFunSoundHorn');    t.togOpt ('togKsFunSoundGun', 'KsFunSoundGun');
            t.changeOpt ('togURLF1', 'soundURLF1');    t.changeOpt ('togURLF1vol', 'URLsonF1vol');    t.changeOpt ('togURLF2', 'soundURLF2');    t.changeOpt ('togURLF2vol', 'URLsonF2vol');    t.changeOpt ('togURLF3', 'soundURLF3');    t.changeOpt ('togURLF3vol', 'URLsonF3vol');    
            t.changeStyleOpt ('KsToOverview', 'toOverview');
            t.changeStyleOpt ('KsToReports', 'toReports');
            t.changeStyleOpt ('KsToMarches', 'toMarches');
            t.changeStyleOpt ('KsToTrain', 'toTrain');
            t.changeStyleOpt ('KsToAutoTrain', 'toAutoTrain');
            t.changeStyleOpt ('KsToThroneStuff', 'toThroneStuff');
            t.changeStyleOpt ('KsToSearch', 'toSearch');
            t.changeStyleOpt ('KsToPlayer', 'toPlayer');
            t.changeStyleOpt ('KsToBuild', 'toBuild');
            t.changeStyleOpt ('KsToTransport', 'toTransport');
            t.changeStyleOpt ('KsToReassign', 'toReassign');
            t.changeStyleOpt ('KsToAutoCraft', 'toAutoCraft');
            t.changeStyleOpt ('KsToFarm', 'toFarm');
            t.changeStyleOpt ('KsToCrest', 'toCrest');
            t.changeStyleOpt ('KsToDarkForest', 'toDarkForest');
            t.changeStyleOpt ('KsToRaid', 'toRaid');
            t.changeStyleOpt ('KsToApothecary', 'toApothecary');
            t.changeStyleOpt ('KsToScoutAlliance', 'toScoutAlliance');
            t.changeStyleOpt ('KsToWild', 'toWild');
            t.changeStyleOpt ('KsToKnights', 'toKnights');
            t.changeStyleOpt ('KsToOptions', 'toOptions');
            t.changeStyleOpt ('KsToUserTab', 'toUserTab');
            t.changeStyleOpt ('KsToKoCScripts', 'toKoCScripts');

            t.togOpt ('togAllMembers', 'enhanceViewMembers', AllianceReports.enable_viewmembers);
            t.togOpt ('ptEnableFoodWarnTchat', 'enableFoodWarnTchat', FoodAlerts.init);
            t.togOpt ('ptAllowWinMove', 'ptWinDrag', mainPop.setEnableDrag);
            t.togOpt ('ptAllowTransparent', 'KsTransparence');
            t.togOpt ('ptEnableFoodWarn', 'enableFoodWarn');
            t.togOpt ('togChatStuff', 'chatEnhance', ChatStuff.setEnable, ChatStuff.isAvailable);
            t.togOpt ('togKnightSelect', 'fixKnightSelect', AttackDialog.setEnable, AttackDialog.isKnightSelectAvailable);
            t.togOpt ('togAttackPicker', 'attackCityPicker', AttackDialog.setEnable, AttackDialog.isCityPickerAvailable);
            t.togOpt ('togEnhanceMsging', 'enhanceMsging', messageNav.setEnable, messageNav.isAvailable);
            t.togOpt ('togCoordBox', 'mapCoordsTop', CoordBox.setEnable, CoordBox.isAvailable);
            t.togOpt ('togMightKoCBugFix', 'showMightKoCBugFix');
            t.togOpt ('togResKoCBugFix', 'showResKoCBugFix');
            t.togOpt ('togKsInfoBox', 'showKsInfoBox');
            t.togOpt ('togWhisperOn', 'WhisperOn');
            t.togOpt ('togAttaqueOn', 'AttaqueOn');
            t.togOpt ('togWildSoundOn', 'WildSoundOn');
            t.togOpt ('togFoodSoundOn', 'FoodSoundOn');
            t.togOpt ('togEclaireurOn', 'EclaireurOn');
            t.togOpt ('user_icon', 'icon_chat');
            t.togOpt ('user_iconFlag', 'icon_chatFlag');
            t.togOpt ('MapExtra', 'MapShowExtra');
            t.togOpt ('deletetoggle', 'DeleteMsg');
            t.togOpt ('delete4toggle', 'DeleteMsgs4');
            t.togOpt ('deletes5toggle', 'DeleteMsgs5');
            t.togOpt ('deletes6toggle', 'DeleteMsgs6');
            t.togOpt ('deletes0toggle', 'DeleteMsgs0');
            t.togOpt ('deletes1toggle', 'DeleteMsgs1');
            t.togOpt ('deletes2toggle', 'DeleteMsgs2');
            t.togOpt ('deletes3toggle', 'DeleteMsgs3');
            t.togOpt ('HelReq', 'HelpRequest');
            t.togOpt ('DelReq', 'DeleteRequest');
            t.togOpt ('togEnableButtler', 'enableButtler');
            t.changeOpt ('pbeverymins', 'pbEveryMins' , RefreshEvery.setTimer);
            t.changeOpt ('togCustomWideScreenSize', 'customWideScreenSize');
            t.togOpt ('pbEveryEnable', 'pbEveryEnable', RefreshEvery.setEnable);
            t.togOpt ('pbChatREnable', 'pbChatOnRight', WideScreen.setChatOnRight);
            t.togOpt ('pbWMapEnable', 'pbWideMap', WideScreen.useWideMap);
            t.togOpt ('togAllRpts', 'enhanceARpts', AllianceReports.enable);
            ById('pcalertEnable').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pbalertDefend').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertPrefix').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertQG').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertScout').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertWild').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertTroops').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertTroops2').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertEmbassy').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertFletching').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertMarechal').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertdefBoost').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertMytroops').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertFood').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertDefense').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertHQ').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertSendEmail').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertEmailAddress').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertToken').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertSendAsWhisper').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertSendToAlly').addEventListener ('change', t.e_alertOptChanged, false);
            ById('Ksalertraid').addEventListener ('change', t.e_alertOptChanged, false);
            ById('Ksalertautofo').addEventListener ('change', t.e_alertOptChanged, false);
            ById('Ksalertautots').addEventListener ('change', t.e_alertOptChanged, false);
            ById('Ksalertappro').addEventListener ('change', t.e_alertOptChanged, false);

            ById('pcalertTroneRange').addEventListener ('change', t.e_alertOptChanged, false);
            ById('pcalertTroneRangeDebuff').addEventListener ('change', t.e_alertOptChanged, false);
            
            ById('Ksalertthrone').addEventListener ('change', t.e_alertOptChanged, false);
            ById('KsalertTSet').value = Options.alertConfig.throneSet;
            ById('KsalertTSet').addEventListener ('change', t.e_alertOptChanged, false);
            ById('KsalertthroneRet').addEventListener ('change', t.e_alertOptChanged, false);        
            ById('KsalertTSetRet').value = Options.alertConfig.throneSetRet;
            ById('KsalertTSetRet').addEventListener ('change', t.e_alertOptChanged, false);
            ById('KsalertthroneMin').addEventListener ('change', t.e_alertOptChanged, false);

            ById('Ksdeletetimer').addEventListener ('change', function () {
                if (parseInt(ById('Ksdeletetimer').value) < 2) {
                    ById('Ksdeletetimer').value=2;
                }
                Options.DeleteTimerMinute = ById('Ksdeletetimer').value;
                saveOptions();
            }, false);

            t.changeOpt ('togURL1', 'URLson1');
            t.changeOpt ('togURLson1Vol', 'URLson1Vol');
            t.changeOpt ('KspopupBorderRadius', 'popupBorderRadius');
            t.changeOpt ('togURL2', 'URLson2');
            t.changeOpt ('togURLson2Vol', 'URLson2Vol');
            t.changeOpt ('togURL4', 'URLson4');
            t.changeOpt ('togURLson4Vol', 'URLson4Vol');
            t.changeOpt ('togURL5', 'URLson5');
            t.changeOpt ('togURLson5Vol', 'URLson5Vol');
            t.changeOpt ('togURL6', 'URLson6');
            t.changeOpt ('togURLson6Vol', 'URLson6Vol');
            t.changeOpt ('togURL3', 'URLicon3');
            t.changeOpt ('togMultiUpdateSoundEnable', 'multiUpdateSoundEnable');
            t.changeOpt ('togMultiUpdateSoundVol', 'multiUpdateSoundVol');

            ById("KsDefURL3").addEventListener ('click', function () {
                Options.URLicon3 = 'http://kofc.god-like.info/multi/img/pdx-useravatar.png';
                ById('togURL3').value='http://kofc.god-like.info/multi/img/pdx-useravatar.png';
                saveOptions();
            }, false);

            ById("KsDefURL1").addEventListener ('click', function () {
                Options.URLson1 = 'http://sfx.god-like.info/fluestersound.mp3';
                ById('togURL1').value='http://sfx.god-like.info/fluestersound.mp3';
                saveOptions();
            }, false);
            ById("KsDefURL2").addEventListener ('click', function () {
                Options.URLson2 = 'http://sfx.god-like.info/sirene.mp3';
                ById('togURL2').value='http://sfx.god-like.info/sirene.mp3';
                saveOptions();
            }, false);
            ById("KsDefURL4").addEventListener ('click', function () {
                Options.URLson4 = 'http://sfx.god-like.info/scouts.mp3';
                ById('togURL4').value='http://sfx.god-like.info/scouts.mp3';
                saveOptions();
            }, false);
            ById("KsDefURL5").addEventListener ('click', function () {
                Options.URLson5 = 'http://sfx.god-like.info/phone.mp3';
                ById('togURL5').value='http://sfx.god-like.info/phone.mp3';
                saveOptions();
            }, false);
            ById("KsDefURL6").addEventListener ('click', function () {
                Options.URLson6 = 'http://sfx.god-like.info/phone.mp3';
                ById('togURL6').value='http://sfx.god-like.info/phone.mp3';
                saveOptions();
            }, false);
            ById("PDXDefURLF1").addEventListener ('click', function () {
                Options.URLson6 = 'http://sfx.god-like.info/war-alarm.mp3';
                ById('togURL6').value='http://sfx.god-like.info/war-alarm.mp3';
                saveOptions();
            }, false);
            ById("PDXDefURLF2").addEventListener ('click', function () {
                Options.URLson6 = 'http://sfx.god-like.info/hupenchaos.mp3';
                ById('togURL6').value='http://sfx.god-like.info/hupenchaos.mp3';
                saveOptions();
            }, false);
            ById("PDXDefURLF3").addEventListener ('click', function () {
                Options.URLson6 = 'http://sfx.god-like.info/gun.mp3';
                ById('togURL6').value='http://sfx.god-like.info/gun.mp3';
                saveOptions();
            }, false);


            ById('optHauteurBoite').addEventListener ('change', function () {
                var x = ById('optHauteurBoite').value;
                if (isNaN(x) || x<600 || x>1000){
                    ById('optHauteurBoite').value = 700;
                }
                Options.HauteurBoite = x;
                saveOptions();
            }, false);

            var checkbox = ById('togEnhanceMsging');
            if (Options.enhanceMsging)
                checkbox.checked = true;
            checkbox.addEventListener ('change', function (){messageNav.setEnable(ById('togEnhanceMsging').checked)}, false);

        } catch (e) {
            t.cont.innerHTML = '<PRE>'+ e.name +': '+ e.message +'</pre>';
        }

    },
    
    EmoClick: function(what) {
        document.getElementById ("mod_comm_input").value += " " + what + " ";
    },
    EmoHelp : function (){
        var t = Tabs.Options;
        unsafeWindow.KsEmoClick = t.EmoClick;
        var helpText = '<DIV style="max-height:400px;">';
        helpText += '<TABLE width=98% cellspacing=0 cellpadding=2 border=0 bordercolor=black class=pdxTab><tr>';
        var row=0;
        for (k in Smileys) {
            helpText += '<TR><TD><img class=emoicon src=\"'+Smileys[k]+'\" onclick="KsEmoClick(\''+k+'\')"></td><TD><font size=1>'+k+'</td></tr>';
        }
        helpText += '</table></div>';

        var inputtext=ById('mod_comm_input');
        var pop = new CPopup ('EmoHelp', 0, 0, 115, 455, true);
        pop.getMainDiv().innerHTML = helpText;
        pop.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.mainSmileys+'</div>';
        pop.show (true);

        ById("EmoHelp_outer").style.top = (getOffset(inputtext).top+30) +'px';
        ById("EmoHelp_outer").style.left = (getOffset(inputtext).left+230) +'px';
    },

    hide : function (){
    },
    loadUrl : function (url){
        var t = Tabs.Options;
        t.mss.load (1, url, true);
        ById('optionsLoadSWF').innerHTML = ''+culang.optionsChargement+'';
    },
    e_swfLoaded : function (){
        var t = Tabs.Options;
        ById('boLoadingSwf').style.display = 'none';
        ById('boSoundOpts').style.display = 'inline';
        t.volSlider.setValue (Options.alertSound.volume/100);
        t.loadUrl (Options.alertSound.soundUrl);
        setTimeout (function (){t.mss.setVolume (1, Options.alertSound.volume);}, 500);
        if (Options.alertSound.alarmActive && Options.alertSound.expireTime>unixTime())   {
            t.soundTheAlert();
        }
    },
    e_volChanged : function (val){
        var t = Tabs.Options;
        ById('boVolOut').innerHTML = parseInt(val*100);
        Options.alertSound.volume = parseInt(val*100);
        t.mss.setVolume (1, Options.alertSound.volume);
    },
changeColors : function (valueId, optionName, callOnChange){
    var t = Tabs.Options;
    var e = document.getElementById(valueId);
    e.value = Colors[optionName];
    e.addEventListener ('change', eventHandler, false);
    function eventHandler (){
      Colors[optionName] = this.value;
      saveColors();
      if (callOnChange)
        callOnChange (this.value);
    }
  },
    togOpt : function (checkboxId, optionName, callOnChange){
        var t = Tabs.Options;
        var checkbox = ById(checkboxId);
        if (Options[optionName])
            checkbox.checked = true;
        checkbox.addEventListener ('change', eventHandler, false);
        function eventHandler (){
            Options[optionName] = this.checked;
            saveOptions();
            if (callOnChange)
                callOnChange (this.checked);

            if (optionName=="DeleteMsgs5" || optionName=="DeleteMsgs6" || "DeleteMsgs4" || optionName=="DeleteMsg" || optionName=="DeleteMsgs0" || optionName=="DeleteMsgs1" || optionName=="DeleteMsgs2" || optionName=="DeleteMsgs3") {
                DeleteReports.init();
            }
        }
    },
    changeOpt : function (valueId, optionName, callOnChange){
        var t = Tabs.Options;
        var e = ById(valueId);
        e.value = Options[optionName];
        e.addEventListener ('change', eventHandler, false);
        function eventHandler (){
            Options[optionName] = this.value;
            saveOptions();
            if (callOnChange)
                callOnChange (this.value);
        }
    },

    changeStyleOpt : function (valueId, optionName, callOnChange){
        var t = Tabs.Options;
        var e = ById(valueId);
        e.value = TabOptions[optionName];
        e.addEventListener ('change', eventHandler, false);
        function eventHandler (){
            TabOptions[optionName] = this.value;
            saveTabOptions();
            if (callOnChange)
                callOnChange (this.value);
        }
    },
    e_watchChanged : function (){
        GlobalOptions.pbWatchdog = ById('KsWatchEnable').checked;
        GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
    },
    e_wideChanged : function (){
        GlobalOptions.pbWideScreen = ById('boWideOpt').checked;
        GM_setValue ('KsOptions_??', JSON2.stringify(GlobalOptions));
    },

    e_alertOptChanged : function (){
        Options.alertConfig.aChat = ById('pcalertEnable').checked;
        Options.alertConfig.aPrefix=ById('pcalertPrefix').value;
        Options.alertConfig.scouting=ById('pcalertScout').checked;
        Options.alertConfig.wilds=ById('pcalertWild').checked;
        Options.alertConfig.MonQG=ById('pcalertQG').checked;
        Options.alertConfig.embassy=ById('pcalertEmbassy').checked;
        Options.alertConfig.fletching=ById('pcalertFletching').checked;
        Options.alertConfig.marechal=ById('pcalertMarechal').checked;
        Options.alertConfig.defBoost=ById('pcalertdefBoost').checked;
        Options.alertConfig.mytroops=ById('pcalertMytroops').checked;
        Options.alertConfig.food=ById('pcalertFood').checked;
        Options.alertConfig.defense=ById('pcalertDefense').checked;
        Options.alertConfig.defence=ById('pbalertDefend').checked;
        Options.alertConfig.hq=ById('pcalertHQ').options[ById('pcalertHQ').selectedIndex].value;
        Options.alertConfig.sendEmail=ById('pcalertSendEmail').checked;
        Options.alertConfig.emailAddress=ById('pcalertEmailAddress').value;
        Options.alertConfig.token=ById('pcalertToken').value;
        Options.alertConfig.sendasWhisper=ById('pcalertSendAsWhisper').checked;
        Options.alertConfig.sendtoAlly=ById('pcalertSendToAlly').checked;
        Options.alertConfig.raid=ById('Ksalertraid').checked;
        Options.alertConfig.appro=ById('Ksalertappro').checked;
        Options.alertConfig.autofo=ById('Ksalertautofo').checked;
        Options.alertConfig.autots=ById('Ksalertautots').checked;
        Options.alertConfig.TroneRange=ById('pcalertTroneRange').checked;
        Options.alertConfig.TroneRangeDebuff=ById('pcalertTroneRangeDebuff').checked;
        Options.alertConfig.changeThrone=ById('Ksalertthrone').checked;
        Options.alertConfig.throneSet=ById('KsalertTSet').value;
        if (!Options.alertConfig.changeThrone) {
            ById('KsalertthroneRet').checked = false;
            Options.alertConfig.RecentActivity = false;
        }
        Options.alertConfig.returnThrone=ById('KsalertthroneRet').checked;
        if (!Options.alertConfig.returnThrone) {
            Options.alertConfig.RecentActivity = false;
        }
        Options.alertConfig.throneSetRet=ById('KsalertTSetRet').value;
        Options.alertConfig.returnThroneMin=parseInt(ById('KsalertthroneMin').value);
        var mt = parseInt(ById('pcalertTroops').value);
        if (mt<1 || mt>120000){
            ById('pcalertTroops').value = Options.alertConfig.minTroops;
            ById('pcalerterr').innerHTML = '<font color=#600000><B>'+culang.mainInvalid+'</b></font>';
            setTimeout (function (){ById('pcalerterr').innerHTML =''}, 2000);
            return;
        }
        Options.alertConfig.minTroops = mt;
        var mt = parseInt(ById('pcalertTroops2').value);
        if (mt<1 || mt>120000){
            ById('pcalertTroops2').value = Options.alertConfig.minTroops2;
            ById('pcalerterr').innerHTML = '<font color=#600000><B>'+culang.mainInvalid+'</b></font>';
            setTimeout (function (){ById('pcalerterr').innerHTML =''}, 2000);
            return;
        }
        Options.alertConfig.minTroops2 = mt;
        saveOptions();
    },
}
//</editor-fold>

/************************************************************************************
*                        KOC POWER - MULTI TABS                                                                      *
************************************************************************************/
eval(GM_getResourceText("MULTI_TABS"));
var SpamEvery  = {
    timer : null,

    init : function (){
        if (Options.spamOptions.spamMinGlobal < 1)
            Options.spamOptions.spamMinGlobal = 1;
        SpamEvery.setEnable (Options.spamOptions.enableGlobal);
    },
    setEnable : function (tf){
        var t = SpamEvery;
        clearTimeout (t.timer);
        if (tf)
            t.timer = setTimeout (t.count, '60000');
    },
    count : function (){ var t = SpamEvery; 
        if (Options.spamOptions.atime > Options.spamOptions.spamMinGlobal) {  
            Options.spamOptions.atime = 2;  t.doit ();   
        } else {  
            Options.spamOptions.atime = (Options.spamOptions.atime + 1);  
            SpamEvery.init ();   
        }
    },
    doit : function (){

        actionLog (''+culang.mainSpam+'','<b>'+culang.spamGlobalChat+'</b>: <span class"boldRed">'+ Options.spamOptions.spamMinGlobal +'</span> '+culang.spamActionLogMessage+'<BR><sup>'+Options.spamOptions.spamMessageGlobal+'</sup>');
        sendChat ("/g "+culang.prefixSpam+" "+  Options.spamOptions.spamMessageGlobal);
        SpamEvery.init ();
    }
}

var SpamEveryA  = {
    timer : null,

    init : function (){
        if (Options.spamOptions.spamMinAlliance < 1)
            Options.spamOptions.spamMinAlliance = 1;
        SpamEveryA.setEnableA (Options.spamOptions.enableAlliance);
    },
    setEnableA : function (tf){
        var t = SpamEveryA;
        clearTimeout (t.timer);
        if (tf)
            t.timer = setTimeout (t.count, 60000);
    },
    count : function (){
        var t = SpamEveryA;
        Options.spamOptions.atimea = parseIntNan(Options.spamOptions.atimea);
        if (Options.spamOptions.atimea > Options.spamOptions.spamMinAlliance) {
            Options.spamOptions.atimea = 2;  t.doit ();
        } else {
            Options.spamOptions.atimea = (Options.spamOptions.atimea + 1);
            SpamEveryA.init ();
        }
    },

    doit : function (){
        actionLog (''+culang.mainSpam+'','<b>'+culang.spamAllianceChat+'</b>: <span class"boldRed">'+ Options.spamOptions.spamMinAlliance +'</span> '+culang.spamActionLogMessage+'<BR><sup>'+Options.spamOptions.spamMessageAlliance+'</sup>');
        sendChat ("/a "+culang.prefixSpam+" "+  Options.spamOptions.spamMessageAlliance);
        SpamEveryA.init ();
    }
}
function actionLog (ou,msg){
    Tabs2.ActionLog.log (msg,ou);
}

//<editor-fold desc="SPLIT:messageNav.js">
/************************************************************************************
*                        KOC POWER - MESSAGE STUFF                                    *
************************************************************************************/
var messageNav = {
    mmFunc : null,
    MapFunc :null,
    mmsFunc : null,
    init : function (){
        t = messageNav;
        t.MapFunc = new CalterUwFunc ('modal_maptile', [[/}\s*$/, ';setTimeout(function() { KsMdal_hook(j); },0); }']]);
        //t.mmFunc = new CalterUwFunc ('modal_messages', [[/}\s*$/, ';setTimeout(messageNav_hook,0); }']]);
        //t.mmsFunc = new CalterUwFunc ('modal_messages_send', [[/{\s*var params/i, '{if (modal_messages_send_hook()) return; var params']]);
        unsafeWindow.KsMdal_hook = t.testons;
        //unsafeWindow.messageNav_hook = t.hook;
        //unsafeWindow.modal_messages_send_hook = t.msgSendHook;
        t.MapFunc.setEnable (true);
        //t.mmFunc.setEnable (true);
        //t.mmsFunc.setEnable (true);

    },
    setEnable : function (tf){
    },
    isAvailable : function (){
        t = messageNav;
        return t.mmFunc.isAvailable();
    },
    testons :function(uid) {
        if (uid!=null && uid > 0) {
            var div = ById('contextMenu');
            var scr = document.createElement('div');
            scr.style.padding = "5px";
            scr.innerHTML =""+culang.movementPlayerCheckSearch+"";
            div.appendChild(scr);
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.checkArr = uid;
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getOnline.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    var p = rslt.data;
                    if (p[uid] == true) {
                        m = '<span style="color:green; font-weight:bold;">'+culang.movementPlayerCheckOn+'</span>';
                        scr.innerHTML= m;
                    } else {
                        m = '<span style="color:maroon; font-weight:bold;">'+culang.movementPlayerCheckOff+'</span>';
                        scr.innerHTML= m;
                        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
                        params.pid = uid;
                        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/viewCourt.php" + unsafeWindow.g_ajaxsuffix, {
                            method: "post",
                            parameters: params,
                            onSuccess: function (rslt) {
                                if (rslt.ok) {
                                    scr.innerHTML += '<br><u>'+culang.mainLastLogin+'</u>:<br>'+rslt.playerInfo.lastLogin+'';
                                }

                            },onFailure: function (rslt) {},

                        });

                    }
                },onFailure: function (rslt) {},
            });
        }
    },
    hook : function (){
        if (!Options.enhanceMsging)
            return;
        var div = ById('modal_msg_view_actions');
        div = ById('modal_msg_write_to').parentNode;
        div.innerHTML = '<TABLE><TR><TD class=xtab><b>A: </b> <INPUT type=text id=modal_msg_write_to></td>\
    <TD class=xtab></td></tr>\
    <tr><td></td><td></td></tr></table>\
    <table><tr><TD colspan=2><SPAN id=pt2fwdbut></span></td></tr></table>';
        ById('pt2fwdbut').innerHTML="CC: <INPUT type=text id=message_cc>";
    },
    eventForward : function (){
        ById('modal_msg_write_subj').value = "TR: " + ById('modal_msg_view_subj').innerHTML.toString().stripTags();
        ById('modal_msg_write_to').value = '';
        var from = ById('modal_msg_view_from').children[0].innerHTML;
        var body = ById('modal_msg_view_body').innerHTML.replace(/\n/g, '').replace(/<br>/gi, '\n').stripTags().replace (/back$/i, '');
        ById('modal_msg_write_txt').value = '[Message original de '+ from +']\n'+ body;
        unsafeWindow.modal_messages_compose();
    },
    msgSendHook : function (){
        if (!Options.enhanceMsging)
            return;
        var to = ById("modal_msg_write_to").value.trim();
        var chaine = ById("message_cc").value;
        var tableau = chaine.split(";")
        if (tableau.length==0) tableau[0]=chaine;
        for (var i = 0; i < tableau.length; i++) {
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
            params.emailTo = tableau[i] ;
            params.subject = "CC: "+ById("modal_msg_write_subj").value;
            params.message = ById("modal_msg_write_txt").value;
            params.requestType     = 'COMPOSED_MAIL';
            new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                onSuccess: function (rslt) {
                    if (rslt.ok) ById('message_cc').value = "";
                },
            });
        }
        if (to.toLowerCase() != '<officiers>' || getMyAlliance()[0]==0) {
            return false;
        }
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.toIds = getMyAlliance()[0];
        params.subject = ById("modal_msg_write_subj").value +'';
        params.message = ById("modal_msg_write_txt").value;
        params.type = 'alliance';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/sendMessage.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (rslt.ok) {
                    unsafeWindow.Modal.showAlert(unsafeWindow.g_js_strings.modal_messages_send.msgsent);
                    ById('modal_msg_write_to').value = "";
                    ById('modal_msg_write_subj').value = "";
                    ById('modal_msg_write_txt').value = ""
                } else {
                    unsafeWindow.Modal.showAlert(unsafeWindow.g_js_strings.modal_messages_send.enterexistingname)
                }
            },
            onFailure: function () {
                unsafeWindow.Modal.showAlert(unsafeWindow.g_js_strings.modal_messages_send.oopscompose)
            },
        });
        return true;
    },
}


var AttackDialog = {
    init : function (){
        var t = AttackDialog;
        t.modal_attackFunc = new CalterUwFunc ('modal_attack', [[/}\s*$/, ';attackDialog_hook(); }']]);
        unsafeWindow.attackDialog_hook = t.modalAttackHook;
        t.modal_attackFunc.setEnable (true);
    },

    setEnable : function (){
    },

    isKnightSelectAvailable : function (){
        var t = AttackDialog;
        return t.modal_attackFunc.isAvailable();
    },
    isAttackCityPickerAvailable : function (){
        var t = AttackDialog;
        return t.modal_attackFunc.isAvailable();
    },

    modalAttackHook : function (){
        var t = AttackDialog;
        if (Options.fixKnightSelect || Options.attackCityPicker){
            for (var i=1; i<6; i++)
                ById('modal_attack_tab_'+ i).addEventListener('click', t.e_changeMarchType, false);
        }
        if (Options.attackCityPicker){
            setTimeout (t.initCityPicker, 0);
        }
    },

    initCityPicker : function (){
        var t = AttackDialog;
        var div = ById('modal_attack_target_numflag'); // as of KofC version 96;
        var mySpan;
        if (div) {
            div.parentNode.innerHTML += ' &nbsp; <SPAN id=modal_attack_citybuts></span>';
        } else {
            var span = ById('modal_attack_target_coords');   // KofC version 116+;
            span.parentNode.parentNode.firstChild.innerHTML += ' &nbsp; <SPAN id=modal_attack_citybuts></span>';
        }
        new CdispCityPicker ('ptatp', ById('modal_attack_citybuts'), false, t.e_CityButton);
        var cityIdx = Cities.byID[unsafeWindow.currentcityid].idx;
        thisCityBut = ById('ptatp_'+ cityIdx);
        thisCityBut.style.opacity = '0.5';
        thisCityBut.disabled = true;
        if (ById('modal_attack_tab_4').className=='selected' || ById('modal_attack_tab_3').className=='selected')   // don't do for attack or scout
            ById('modal_attack_citybuts').style.display = 'none';
    },

    e_CityButton : function (city){
        ById('modal_attack_target_coords_x').value = city.x;
        ById('modal_attack_target_coords_y').value = city.y;
        unsafeWindow.modal_attack_update_time();
    },

    e_changeMarchType : function (evt){
        var t = AttackDialog;
        var marchType = parseInt(evt.target.id.substr(17));
        if (Options.attackCityPicker){
            if (marchType==3 || marchType==4)
                ById('modal_attack_citybuts').style.display = 'none';
            else
                ById('modal_attack_citybuts').style.display = 'inline';
        }
        if (Options.fixKnightSelect){
            var knightVal = 0;
            var selector = ById('modal_attack_knight');
            if (selector.length>1 && (marchType==4 || marchType==2))   // if 'attack' or 'reinforce'
                knightVal = 1;
            selector.selectedIndex = knightVal;
        }
    },
}
var DispReport = {
    init : function (){
        var t = DispReport;
        t.modal_InboxFunc = new CalterUwFunc ('modal_messages_listshow', [['msghtml.join("");', 'msghtml.join("");dispInbox_hook(rslt,boxType,msghtml);']]);
        uW.dispInbox_hook = t.ModalInboxHook;
        t.modal_InboxFunc.setEnable (Options.enhancedinbox);
    },

    setEnable : function (tf){
        var t = DispReport;
        t.modal_InboxFunc.setEnable (tf);
    },

    isDispReportAvailable : function (){
        var t = DispReport;
        return t.modal_InboxFunc.isAvailable();
    },

    ModalInboxHook : function (rslt,boxType,msghtml){
        var t = DispReport;
        if(boxType == 'inbox'){
            msgBody = document.getElementById('modal_msg_list');
            var a = document.createElement('a');
            a.className='inlineButton20Red';
            a.innerHTML='<span>'+culang.giftsDeleteReports+'</span>';
            a.style.float = 'left';
            a.style.position = 'relative';
            a.style.top = '10px';
            a.style.left = '25px';
            a.addEventListener('click', t.checkinbox, false);
            var div = document.createElement('span');
            div.appendChild(a);
            msgBody.appendChild(div);
        }
    },

    checkinbox : function(evt){
        var t = DispReport;
        var body = document.getElementById('tbl_messages');
        var trs=body.getElementsByTagName('tr');
        var reports = [];
        for(var i=0; i<trs.length; i++){
            var tds = trs[i].getElementsByTagName('td');
            for(var j=0; j<tds.length; j++){
                if(tds[j].className == 'chkcol'){
                    var checkbox = tds[j];
                }
                if(tds[j].className == 'nmcol'){
                    var sender = tds[j];
                }
                if(tds[j].className == 'subjcol'){
                    var subject = tds[j];
                }
            }
            reports.push({checkbox:checkbox,sender:sender,subject:subject});
        }
        t.parseGiftReport(reports);
    },

    parseGiftReport : function(rpts){
        var t = DispReport;
        for(var i=0; i<rpts.length; i++){
            if((rpts[i].subject.innerHTML.indexOf(''+culang.getGiftDeleteButton+'') >= 0 ||
                    rpts[i].subject.innerHTML.indexOf('New Gift Received!') >= 0 ||
                    rpts[i].subject.innerHTML.indexOf('Neues Geschenk erhalten!') >= 0 ||
                    rpts[i].subject.innerHTML.indexOf('Nouveaux Cadeaux') >= 0 ||
                    rpts[i].subject.innerHTML.indexOf('Nuevo regalo recibido') >= 0 ||
                    rpts[i].subject.innerHTML.indexOf('Nuovo Regalo ricevuto') >= 0 
                ) && 
                rpts[i].sender.innerHTML.indexOf('Kingdoms Of Camelot') >= 0
            ){
                rpts[i].checkbox.firstChild.checked = true;
            }
        }
        uW.messages_action("delete","tbl_messages");
    }

}
//</editor-fold>
//<editor-fold desc="SPLIT:AllianceReports.js">
/************************************************************************************
 *                        KOC POWER - ALLIANCE REPORTS                                *
 ************************************************************************************/
var AllianceReports = {
    checkPeriod : 300,
    allianceNames : [],
    saveArfunc : unsafeWindow.allianceReports,
    init : function (){
        t = AllianceReports;
        t.enable (Options.enhanceARpts);
        t.marvFunc = new CalterUwFunc ('modal_alliance_report_view', [['getReportDisplay', 'getReportDisplay_hook2']]);
        t.memListFunc = new CalterUwFunc ('membersInfo', [['commonstr.might','commonstr.might + "</td><td class=colcities>" + g_js_strings.commonstr.cities + "</td><td class=colava>Avatar</td><td class=collast>" + g_js_strings.membersInfo.lastonline'],['memberInfo[key].prestige', 'memberInfo[key].prestige+ "</td>");memhtml.push("<td class=colcities>" + memberInfo[key].cities + "</td><td class=colava><img width=35 src=" + memberInfo[key].avatarurl + "></td>");memhtml.push("<td class=collast>" + memberInfo[key].lastLogin']]);
        unsafeWindow.getReportDisplay_hook2 = t.getReportDisplayHook;
        unsafeWindow.getmembersInfo_hook = t.getMembersInfoHook;
        t.marvFunc.setEnable (true);
        t.enable_viewmembers(Options.enhanceViewMembers);
    },
    getReportDisplayHook : function (a, b){
        var x = '';
        try {
            x = unsafeWindow.getReportDisplay(a,b);
        } catch (e){
            x = 'Error formatting report: '+ e;
        }
        return x;
    },
    enable_viewmembers : function (tf){
        t = AllianceReports;
        t.memListFunc.setEnable (tf);
    },
    enable : function (tf){
        t = AllianceReports;
        if (tf)
            unsafeWindow.allianceReports = t.myAllianceReports;
        else
            unsafeWindow.allianceReports = t.saveArfunc;
    },
    myAllianceReports : function (pageNum){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if (pageNum)
            params.pageNo = pageNum;
        params.group = "a";
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                displayReports (rslt.arReports, rslt.arPlayerNames, rslt.arAllianceNames, rslt.arCityNames, rslt.totalPages);
            },
            onFailure: function (rslt) {
            },
        }, false);

        function displayReports (ar, playerNames, allianceNames, cityNames, totalPages){
            var msg = new Array();
            var myAllianceId = getMyAlliance()[0];
            msg.push ("<STYLE>.msgviewtable tbody .myCol div {margin-left:5px; overflow:hidden; white-space:nowrap; color:#000}\
            .msgviewtable tbody .myHostile div {color:#900}\
            .msgviewtable tbody .myGray div {color:#666}\
            .msgviewtable tbody .myRein div {color:#090}\
            .msgviewtable tbody .myWarn div {color:#442200}\
            </style>");
            msg.push("<div class='modal_msg_reports'>");
            var rptkeys = unsafeWindow.Object.keys(ar);
            if (matTypeof(ar) != 'array') {
                if (Options.allowAlterAR)
                    msg.push("<div id='modal_alliance_reports_tablediv' class='modal_msg_list'><table width=675 cellpadding='0' cellspacing='0' class='msgviewtable reportviewtable alliancetable'>");
                else
                    msg.push("<div id='modal_alliance_reports_tabledivNKA' class='modal_msg_list'><table width=675 cellpadding='0' cellspacing='0' class='msgviewtable reportviewtable alliancetable'>");
                msg.push("<thead><tr><td width=105>"+culang.mainDate+"</td><td width=40>"+culang.mainType+"</td><td width=150>"+culang.mainAttacker+"</td><td>"+culang.mainTarget+"</td><td>"+culang.mainShow+"</td>");
                //msg.push("<td>"+culang.shortDistance+"</td>");
                msg.push("</tr></thead><tbody>");
                for (var i = 0; i < rptkeys.length; i++) {
                    var rpt = ar[rptkeys[i]];
                    var colClass = '"myCol"';
                    rpt.marchType = parseInt(rpt.marchType);
                    rpt.side0AllianceId = parseInt(rpt.side0AllianceId);
                    var targetDiplomacy = getDiplomacy (rpt.side0AllianceId);
                    if (rpt.marchType == 2){
                        colClass = '"myCol myRein"';
                    } else if (rpt.side1AllianceId != myAllianceId){
                        colClass = '"myCol myHostile"';
                    } else {
                        if (parseInt(rpt.side0TileType) < 50){          // if wild
                            if (parseInt(rpt.side0PlayerId) == 0)
                                colClass = '"myCol myGray"';
                            else
                                colClass = '"myCol myWarn"';
                        } else if (parseInt(rpt.side0PlayerId) == 0) {   // barb
                            colClass = '"myCol myGray"';
                        } else {
                            if (targetDiplomacy == ''+culang.kocFriendly+'')
                                colClass = '"myCol myWarn"';
                        }
                    }
                    msg.push ('<tr valign=top');
                    if (i%2 == 0)
                        msg.push(" class=stripe");
                    msg.push("><TD class="+ colClass +"><div>");
                    msg.push(unsafeWindow.formatDateByUnixTime(rpt.reportUnixTime));
                    msg.push ('<BR>Rpt #');
                    msg.push (rpt.reportId);
                    msg.push("</div></td><TD class="+ colClass  +"><div>");
                    if (rpt.marchType == 1)
                        msg.push (unsafeWindow.g_js_strings.commonstr.transport);
                    else if (rpt.marchType == 3)
                        msg.push (unsafeWindow.g_js_strings.commonstr.scout);
                    else if (rpt.marchType == 2)
                        msg.push (culang.mainReinforced);
                    else
                        msg.push (unsafeWindow.g_js_strings.commonstr.attack);
                    msg.push ("</div></td><TD class="+ colClass +"><div>");
                    if (parseInt(rpt.side1PlayerId) != 0)
                        msg.push('<a onclick=getInfoForAnUser("'+parseInt(rpt.side1PlayerId)+'");>'+escape(playerNames["p" + rpt.side1PlayerId])+"</a>");
                    else
                        msg.push ('?'+culang.mainUnknown+'?');
                    msg.push ('&nbsp;<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side1XCoord +','+ rpt.side1YCoord +')</a><bR>');
                    if (rpt.side1AllianceId != myAllianceId){
                        msg.push (allianceNames['a'+rpt.side1AllianceId]);
                        msg.push (' (');
                        msg.push (getDiplomacy(rpt.side1AllianceId));
                        msg.push (')');
                    } else {
                        msg.push ('<BR>');
                    }
                    msg.push ('</div></td>');
                    msg.push ("<TD class="+ colClass  +"><DIV>");
                    var type = parseInt(rpt.side0TileType);
                    if (type < 50){                              // pour la TS
                        msg.push(unsafeWindow.g_mapObject.types[type].toString().capitalize());
                        msg.push(" "+culang.shortLevel+" " + rpt.side0TileLevel)
                        if (parseInt(rpt.side0PlayerId) != 0) {   // IF OWNED, show owner ...
                            msg.push (' [');
                            msg.push ('<a @onclick=getInfoForAnUser("'+parseInt(rpt.side0PlayerId)+'");>' + escape(playerNames["p" + rpt.side0PlayerId])+'</a>');
                            msg.push ('] ');
                        }
                    } else {
                        if (parseInt(rpt.side0PlayerId) == 0) {   //  barb
                            msg.push(unsafeWindow.g_js_strings.commonstr.barbariancamp);
                            msg.push(" "+culang.shortLevel+" " + rpt.side0TileLevel)
                        } else {        // city
                            msg.push ('<a onclick=getInfoForAnUser("'+ rpt.side0PlayerId+'");>' + escape(playerNames["p" + rpt.side0PlayerId])+'</a>');
                            msg.push (' - ');
                            msg.push (cityNames['c'+ rpt.side0CityId]);
                        }
                    }
                    msg.push ('&nbsp;<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ rpt.side0XCoord +','+ rpt.side0YCoord +')</a>');
                    if (rpt.side0AllianceId!=0 && rpt.side0AllianceId!=myAllianceId){
                        msg.push ('<BR>');
                        msg.push (allianceNames['a'+rpt.side0AllianceId]);
                        msg.push (' (');
                        msg.push (targetDiplomacy);
                        msg.push (')');
                    }
                    if (Options.allowAlterAR)
                        msg.push("</div></td><TD class="+ colClass  +"><div><a onclick=' modal_alliance_report_view(\"");   // ONCLICK ???
                    else
                        msg.push("</div></td><TD class="+ colClass  +"><div><a onclick=' ById(\"modal_alliance_reports_tabledivNKA\").id=\"modal_alliance_reports_tablediv\"; modal_alliance_report_view(\"");   // ONCLICK ???
                    msg.push(rpt.reportId);
                    msg.push('",');
                    if (parseInt(rpt.side1AllianceId) == parseInt(Seed.allianceDiplomacies.allianceId))
                        msg.push(1);
                    else
                        msg.push(0);
                    msg.push(",");
                    msg.push(rpt.side0TileType);
                    msg.push(",");
                    msg.push(rpt.side0TileLevel);
                    msg.push(",");
                    msg.push(rpt.side0PlayerId);
                    msg.push(',"');
                    if (parseInt(rpt.side0PlayerId) != 0)
                        msg.push(escape(playerNames["p" + rpt.side0PlayerId]));
                    else
                        msg.push(unsafeWindow.g_js_strings.commonstr.enemy);
                    msg.push('","');
                    if (parseInt(rpt.side0PlayerId) != 0)
                        msg.push(escape(playerNames["g" + rpt.side0PlayerId]));
                    else
                        msg.push(0)
                    msg.push('","');
                    if (parseInt(rpt.side1PlayerId) > 0)
                        msg.push(escape(playerNames["p" + rpt.side1PlayerId]));
                    msg.push('","');
                    if (parseInt(rpt.side1PlayerId) != 0)
                        msg.push(escape(playerNames["g" + rpt.side1PlayerId]));
                    msg.push('",');
                    msg.push(rpt.marchType);
                    msg.push(",");
                    msg.push(rpt.side0XCoord);
                    msg.push(",");
                    msg.push(rpt.side0YCoord);
                    msg.push(",");
                    msg.push(rpt.reportUnixTime);
                    msg.push(",");
                    if (parseInt(rpt.reportStatus) == 2)
                        msg.push(1);
                    else
                        msg.push(0);
                    if (rpt.side1XCoord) {
                        msg.push(",");
                        msg.push(rpt.side1XCoord);
                        msg.push(",");
                        msg.push(rpt.side1YCoord)
                    } else {
                        msg.push(",,");
                    }
                    msg.push(");return false;'><img border=0 src='"+IMGshowButton+"' title='"+culang.mainShow+"'></a></div></td>");
                    //msg.push("<td>123</td>");
                    msg.push("</tr>");
                }
                msg.push("</tbody></table></div>");
            }
            msg.push("</div><div id='modal_report_list_pagination'></div>");
            ById('allianceContent').innerHTML = msg.join("");
            if (pageNum) {
                unsafeWindow.ctrlPagination("modal_report_list_pagination", totalPages, "allianceReports", pageNum)
            } else {
                unsafeWindow.ctrlPagination("modal_report_list_pagination", totalPages, "allianceReports")
            }
        }
    },
}
//</editor-fold>
//<editor-fold desc="SPLIT:FoodAlerts.js">
/************************************************************************************
 *                        KOC POWER - FOOD ALERT                                        *
 ************************************************************************************/
var FoodAlerts = {
    minuteTimer:null,
    init : function (){
        var f = FoodAlerts;
        clearTimeout(f.minuteTimer);
        if (Options.enableFoodWarnTchat)
            f.e_eachMinute();
    },
    minuteTimer : null,
    e_eachMinute : function (){
        var f = FoodAlerts;
        var now = unixTime();
        row = [];
        if (Options.enableFoodWarnTchat)  {
            for(i=0; i < Cities.numCities; i++) {
                var rp = getResourceProduction (Cities.cities[i].id);
                var foodleft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0])/3600;
                var usage = rp[1] - parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][3]);
                row[i] = rp[1] - usage;
                var timeLeft = parseInt(Seed.resources["city" + Cities.cities[i].id]['rec1'][0]) / 3600 / (0-usage) * 3600;
                var msg = '';
                if (timeLeft<0){
                }
                else if (timeLeft<(Options.foodChatWarnHours*3600)) {
                    msg += ''+culang.foodPostLow+' ' + Cities.cities[i].name.substring(0,10) + ' (' +Cities.cities[i].x +','+ Cities.cities[i].y + ') '+culang.foodPostLow2+' ';
                    msg += ''+culang.foodPostLow3+' '+addCommasWhole(foodleft).replace(',',' ').replace(',',' ').replace(',',' ').replace(',',' ')+' ('+timestrShort(timeLeft)+') '+culang.foodPostLow4+' '+addCommas(usage).replace(',',' ').replace(',',' ').replace(',',' ').replace(',',' ')+'/'+culang.shortHour+'';
                    //msg +=  " _______________________________________________ "+
                    //    "$CMSG[" + window.btoa("{msg:\"FA\", foodleft:"+foodleft+", timeLeft:"+timeLeft+",production:"+usage+"}") + "]$";
                    sendChat ("/a " + msg);
                }
            }
            f.minuteTimer = setTimeout(function() {f.e_eachMinute() }, 1800000);
        }
    },
}
//</editor-fold>
//<editor-fold desc="SPLIT:TowerAlerts.js">
/************************************************************************************
 *                        KOC POWER - TOWER ALERT                                        *
 ************************************************************************************/
var TowerAlerts = {
    viewImpendingFunc : null,
    generateIncomingFunc : null,
    fixTargetEnabled : false,
    towerMarches : {},
    init : function (){
        var t = TowerAlerts;

        var s = GM_getValue ('towerMarches_'+getServerId());
        if (s != null) t.towerMarches = JSON2.parse(s);
    },
    postToChatOptions : {aChat:false},
    secondTimer : null,

    setPostToChatOptions : function (obj){
        var t = TowerAlerts;
        t.postToChatOptions = obj;
        clearTimeout(t.secondTimer);
        if (obj.aChat) t.e_eachSecond();
    },
    addTowerMarch : function (m){
        var t = TowerAlerts;
        var now = unixTime();
        for (k in t.towerMarches){
            if (t.towerMarches[k].arrival < now) {
                delete t.towerMarches[k];
            }
        }
        t.towerMarches['m'+m.mid] = {added:now, arrival:parseIntNan(m.arrivalTime) };
        setTimeout (function (){GM_setValue ('towerMarches_' +getServerId(), JSON2.stringify(t.towerMarches));}, 0);
    },
    getTowerMarch : function (mid){
        var t = TowerAlerts;
        return t.towerMarches['m'+mid];
    },
    e_eachSecond : function (){
        var t = TowerAlerts;
        try {
        var now = unixTime();
        dfObj = ById('AttSearch');
        crestObj = ById('Cresttoggle');
        supplyObj = ById('boReapproState');
        var incomming = false;
        if (matTypeof(Seed.queue_atkinc) != 'array'){
            for (var k in Seed.queue_atkinc){
                var m = Seed.queue_atkinc[k];
                if (Options.alertSound.alarmActive && (now > Options.alertSound.expireTime)) {
                    Tabs.Options.stopSoundAlerts();
                    setTimeout(function() {
                        if (ById('botowertab'))
                            ById('botowertab').style.display="none";
                    },2000);
                }
                //laufen noch Angriffe?
                if ((m.marchType==3 || m.marchType==4) && parseIntNan(m.arrivalTime)>now) {
                    incomming = true;
                }
                //neue Angriffe?
                if ((m.marchType==3 || m.marchType==4) && parseIntNan(m.arrivalTime)>now && t.getTowerMarch(m.mid)==null){
                    Options.alertConfig.RecentActivity = true;
                    Options.alertConfig.lastAttack = now;
                    saveOptions();
                    t.addTowerMarch (m);
                    t.postToChat (m, false);
                    if (Options.alertSound.enabled){
                        //Truppenanzahl beachten!!
                        setTimeout(function() {
                            if (ById('botowertab'))
                                ById('botowertab').style.display="block";
                        },2000);
                        Tabs.Options.soundTheAlert(m);
                        if (m.arrivalTime > Options.alertSound.expireTime)
                            Options.alertSound.expireTime = m.arrivalTime;
                    }
                    if (Options.alertConfig.raid){
                        t.StopCityRaids(m.toCityId);
                    }
                    if (Options.alertConfig.autofo) {
                        Options.AttackRunning = false;
                        if (dfObj) dfObj.value = ""+culang.mainDarkForest+" = "+culang.buttonOFF;
                        saveOptions();
                    }
                    if (Options.alertConfig.autots){
                        CrestOptions.Running = false;
                        if (crestObj) crestObj.value = ""+culang.tabLabelCrest+" = "+culang.buttonOFF;
                        // saveCrestOptions();
                    }
                    if (Options.alertConfig.appro){
                        Tabs.Transport.reapproState.running = false;
                        if (supplyObj) supplyObj.value = ""+culang.shrsupply+" = "+culang.buttonOFF;

                    }
                    if (Options.alertConfig.changeThrone){
                        t.changeThrone(Options.alertConfig.throneSet);
                    }
                }
            }
        }
        if (Options.alertConfig.RecentActivity && 
                Options.alertConfig.returnThrone && 
                Options.alertConfig.changeThrone && 
                !incomming) {
            var switchtime = parseIntNan(Options.alertConfig.lastAttack)+Options.alertConfig.returnThroneMin*60;
            if (switchtime < now) {
                t.changeThrone(Options.alertConfig.throneSetRet);
                Options.alertConfig.RecentActivity = false;
                saveOptions();
            }
        }
        } catch (ex) {
            alert(ex.name +': '+ ex.message + " @"+ ex.lineNumber);
        }
        t.secondTimer = setTimeout (t.e_eachSecond, 1000);
    },
    changeThrone : function(preset) {
        var t = TowerAlerts;
        //Aktuelles Set = Wunschset?
        if (Seed.throne.activeSlot == preset) return;
        //Set wechseln
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.ctrl = 'throneRoom\\ThroneRoomServiceAjax';
        params.action = 'setPreset';
        params.presetId = preset;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch53.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
                var rslt = eval("(" + transport.responseText + ")");
                if(rslt.ok){
                    button = '<li id="throneInventoryPreset' + preset + '" class="active">'+preset+'</li>';
                    unsafeWindow.cm.ThroneView.clickActivePreset(button);
                    //Throne Room Organiser
                    for (var i = 1; i<=8; i++) {
                        var b = ById('t_throneInventoryPreset'+i);
                        if (b) {
                            var c = b.className;
                            //alert(c);
                            if (c == 'buy' || c== 'locked') continue;
                            if (i == preset) {
                                b.setAttribute("class", "selected");
                            } else {
                                b.setAttribute("class", "active");
                                b.addEventListener ('mouseover', function(I){
                                    unsafeWindow.cm.ThroneView.boostsTooltip(this, I, I.target.id);
                                }, false);
                                b.addEventListener ('mouseout', function(I){
                                    unsafeWindow.removeTooltip();
                                }, false);
                            }
                        }
                    }
                }
            },
            onFailure: function () {
                return;
            },
        });
    },
    
    StopCityRaids : function (cityId){
        var t = TowerAlerts;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'stopAll';
        params.settings = {};
        params.settings.cityId = cityId;
        new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");
            },
        });
    },
    postToChat: function(m, force){
        var t = TowerAlerts;
        var postOptions = t.postToChatOptions;
        var troopsnames = [''+culang.kocExtraShortSupplyTroop+'', ''+culang.kocExtraShortMilitiaman+'', ''+culang.kocExtraShortScout+'', ''+culang.kocExtraShortPikeman+'', ''+culang.kocExtraShortSwordsman+'', ''+culang.kocExtraShortArcher+'', ''+culang.kocExtraShortCavalry+'', ''+culang.kocExtraShortHeavyCavalry+'', ''+culang.kocExtraShortSupplyWagon+'', ''+culang.kocExtraShortBallista+'', ''+culang.kocExtraShortBatteringram+'', ''+culang.kocExtraShortCatapult+'', ''+culang.kocExtraShortBloodthorn+'', ''+culang.shrexec+'', ''+culang.shrswall+'']; //15.10.2012 Bommel
        var k=Seed.throne.slotEquip[Seed.throne.activeSlot],i=Seed.throne.inventory,e,faction;
        var B=0, w={}, x, C;
        for (var K in k) {
            var F = uW.kocThroneItems[k[K]];
            if (F) {
                x=0;
                for (var M in F.effects) {
                    x++;
                    if (F.quality >= x) {
                        B++;
                        I = uW.cm.thronestats.effects[F.effects[M].id];
                        effects = uW.cm.thronestats.tiers[F.effects[M].id][F.effects[M].tier];
                        C = + effects.base + (F.level * F.level + F.level) * + effects.growth * 0.5;
                        C = Math.ceil(C);
                        if (!F.isBroken) {
                            if (!w[F.effects[M].id]) {
                                w[F.effects[M].id] = {};
                                w[F.effects[M].id].nameitem="";
                            }
                            if (!w[F.effects[M].id].percent) {
                                w[F.effects[M].id].percent = C;
                            } else {
                                w[F.effects[M].id].percent += C;
                            }
                            w[F.effects[M].id].name = I[1];
                            w[F.effects[M].id].nameitem += "(" + F.name + ")<br>";
                        }
                    }
                }
            }
        }
        var tot = [];
        for (i = 0; i < 16; i++)
            tot[i] = 0;

        if (m.marchType == null)
            return;

        if (m.marchType == 3) {
            if (!postOptions.scouting && !force) return;
            atkType = ''+culang.towerSCOUT+'';
        } else {
            if (m.marchType == 4) {
                atkType = ''+culang.towerATTACK+'';
            } else {
                return;
            }
        }

        var target, atkType, who;
        var city = Cities.byID[m.toCityId];
        if (city.tileId == m.toTileId) {
            target = ''+culang.towerCASTLE+' ' + city.name + ' # ' + city.x + ',' + city.y+' #';
            if (postOptions.marechal) {
                var now = unixTime();
                marshallCombatScore = 0;
                var s = Seed.knights['city'+m.toCityId];
                if (s) {
                    s = s["knt" + Seed.leaders['city'+m.toCityId].combatKnightId];
                    if (s){
                        marshallCombatScore = s.combat;
                        // Option du boost par gans de courage (retirer)
                        //if (s.combatBoostExpireUnixtime > now)
                        //    marshallCombatScore *= 1.25;
                    }
                }
                target += ' ('+culang.mainKnights+' ' + parseInt(marshallCombatScore) + ') ';
            }
        }else {
            if (!postOptions.wilds && !force)
                return;
            atkType = ''+culang.towerWILDATTACK+'';
            target = ''+culang.towerWILD+'';
            for (k in Seed.wilderness['city' + m.toCityId]) {
                if (Seed.wilderness['city' + m.toCityId][k].tileId == m.toTileId) {
                    target += ' ' + Seed.wilderness['city' + m.toCityId][k].xCoord + ',' + Seed.wilderness['city' + m.toCityId][k].yCoord+' ';
                    break;
                }
            }
        }
        if (postOptions.defBoost) {
            var c=unsafeWindow.unixtime();
            var boost="";
            if (parseInt(Seed.playerEffects.defExpire)>c)
            {
                var f=parseInt(Seed.playerEffects.defExpire)-c;
                boost = ""+culang.mainSDefense+". 20%";
            }
            if (parseInt(Seed.playerEffects.def2Expire)>c) {
                var f=parseInt(Seed.playerEffects.defExpire)-c;
                boost = ""+culang.mainSDefense+". 50%";
            }
            target += boost;
        }
        if (postOptions.TroneRange || postOptions.TroneRangeDebuff) {
            target += ". "+culang.tabLabelThrone+": ";
            if (postOptions.TroneRange) {
                if (w[5])
                    target+= w[5].percent + " % "+culang.mainRange+" ";
                else
                    target+= "0 % "+culang.mainRange+" ";
            }
            if (postOptions.TroneRangeDebuff) {
                if (w[22])
                    target+= w[22].percent + " % "+culang.mainDebuff+"";
                else
                    target+= "0 % "+culang.mainDebuff+"";
            }

        }
        var attackermight = '';
        var allianceId = '';
        if (Seed.players['u' + m.pid]) {
            who = Seed.players['u' + m.pid].n;
            attackermight = parseInt(Seed.players['u' + m.pid].m);
            allianceId = Seed.players['u' + m.pid].a;
        } else {
            if (m.players && m.players['u' + m.pid]) {
                who = m.players['u' + m.pid].n;
                attackermight = parseInt(m.players['u' + m.pid].m);
                allianceId = m.players['u' + m.pid].a;
            } else {
                who = ''+culang.mainUnknown+'';
            }
        }
        if (m.fromXCoord)
            who += ' '+culang.towerOn+' ' + m.fromXCoord + ',' + m.fromYCoord;
        if (m.knt) {
            if (m.knt['cbt']!=undefined && m.knt['cbt']!=null) who += ' '+culang.mainKnights+' ' + m.knt['cbt'];
        }
        var diplomacy = getDiplomacy(allianceId);
        var arrivingDatetime = new Date();
        arrivingDatetime.setTime(m.arrivalTime * 1000);
        var msg = '';
        var subject = '';

        msg = ''+culang.towerTYPE+' ' + atkType + '. ';
        if (!postOptions.MonQG && parseIntNan(postOptions.hq)>0) {
            var mavilleId=Cities.byID[postOptions.hq];
            if (mavilleId)
                msg += ' '+culang.towerHQ+' ' + mavilleId.x + ','+mavilleId.y+' ';
        }
        if (postOptions.fletching) {
            msg += ''+culang.towerFlechting+' ' + parseInt(Seed.tech['tch13']) + ' ';
        }

        msg += ' '+culang.mainTarget+': ' + target + ' ';
        msg += culang.mainAttacker + ': ' + who + ' (' + addCommas(attackermight).replace(',',' ').replace(',',' ') + ', ' + diplomacy + ').';
        msg +=' '+culang.towerTypeArrival+' ';
        var totTroops = 0;
        for (k in m.unts) {
            var uid = parseInt(k.substr(1));
            msg += m.unts[k] + ' ' + unsafeWindow.unitcost['unt' + uid][0] + ', ';
            totTroops += m.unts[k];
        }

        // le param?rage du GQ ets fait    
        if (parseIntNan(postOptions.hq)>0) {
            if (parseInt(m.toCityId)==parseInt(postOptions.hq)) {
                // si QG 
                if ((totTroops < postOptions.minTroops)) return;

            }
            if (parseInt(m.toCityId)!=parseInt(postOptions.hq)) {
                // si ville secondaires !
                if ((totTroops < postOptions.minTroops2)) return;

            }
        } else {
            if ((totTroops < postOptions.minTroops) && !force)
                return;
        }
        msg = msg.slice(0, -2);
        msg += ' ('+culang.mainArrival+': ' + unsafeWindow.timestr(parseInt(m.arrivalTime - unixTime())) + ' - ' + arrivingDatetime.toLocaleTimeString() +').' ;
        var msgpart1='';
        if (parseInt(Seed.citystats["city" + m.toCityId].gate) == 0 && Options.alertConfig.defence==true) {
            msg += ' '+culang.towerTypeCastle+' ';
        }
        if (parseInt(Seed.citystats["city" + m.toCityId].gate) == 1 && Options.alertConfig.defence==true) {
            msg += ' '+culang.towerTypeDefense+' ';
        }
        if (city.tileId == m.toTileId) {
            var emb = getCityBuilding(m.toCityId, 8);
            if (emb.count <= 0) {
                msg += ' '+culang.towerNoEmbassy+'';
                var msgpart1 = msg;
                msg ='';
            }
            if (emb.count > 0) {
                var availSlots = emb.maxLevel;
                for (k in Seed.queue_atkinc) {
                    if (Seed.queue_atkinc[k].marchType == 2 && Cities.byID[Seed.queue_atkinc[k].fromCityId] == null) {
                        --availSlots;
                    }
                }
                msg += ' '+culang.towerMyEmbassy+' (' + availSlots + '/' + emb.maxLevel + ')';
                var msgpart1 = msg;
                msg ='';
                if (postOptions.embassy) {
                    var rownum = 0;
                    enc = {};
                    numSlots = 0;
                    if (matTypeof(Seed.queue_atkinc) != 'array') {
                        for (k in Seed.queue_atkinc) {
                            march = Seed.queue_atkinc[k];
                            if (march.marchType == 2) {
                                ++numSlots;
                                city = march.toCityId;
                                from = march.fromPlayerId;
                                if (!enc[city])
                                    enc[city] = {};
                                if (!enc[city][from])
                                    enc[city][from] = [];
                                s = [];
                                s[0] = parseInt(march.knightCombat);
                                for (i = 1; i < 16; i++) {
                                    if (Options.encRemaining)
                                        s[i] = parseInt(march['unit' + i + 'Return']);
                                    else
                                        s[i] = parseInt(march['unit' + i + 'Count']);
                                }
                                enc[city][from].push(s);
                            }
                        }
                    }
                    dest = m.toCityId;
                    var embassyOccupied = false;
                    if (enc[dest]) {
                        embassyOccupied = true;
                        msg += ' '+culang.towerTypeEmbassy+' ';
                        for (p in enc[dest]) {
                            try {
                                if (Seed.players['u' +p]) {
                                    player = Seed.players['u' + p].n;
                                } else {
                                    if (m.players && m.players['u' + p]) {
                                        player = m.players['u' + p].n;
                                    } else {
                                        player = ''+culang.mainUnknown+'';
                                    }
                                }
                            }
                            catch (err) {
                                player = '???';
                            }
                            for (j = 0; j < enc[dest][p].length; j++) {
                                knight = '';
                                if (enc[dest][p][j][0] > 0)
                                    knight = ' (' + enc[dest][p][j][0] + ')';
                                var slot = j + 1;
                                msg += '['+culang.towerEmbassySlot+'' + slot + ': ' + player + knight + '->';
                                for (i = 1; i < 16; i++) {
                                    num = enc[dest][p][j][i];
                                    if (num > 0)
                                        msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[i - 1] + ', ';
                                    tot[i] += num;
                                }
                                msg += ']';
                            }//for (j=0; j<enc[dest][p].length; j++)
                        }//for (p in enc[dest])
                    }//if (enc[dest])

                }// if (postOptions.embassy)
            }//if (emb.count > 0)
        }
        var msgpart2 = msg;
        msg ='';
        if (postOptions.mytroops) {
            msg += ' '+culang.towerTypeMyTroops+' ';
            cityID = 'city' + m.toCityId;
            for (r = 1; r < 16; r++) {
                num = parseInt(Seed.units[cityID]['unt' + r]);
                tot[r] += num;
                if (num > 0)
                    msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[r - 1] + ', ';
            }
            msg += '.';
        }
        var msgpart3 = msg;
        msg ='';
        if (embassyOccupied) {
            msg += ' '+culang.towerTypeTotal+' ';
            for (r = 1; r < 16; r++) {
                num = parseInt(tot[r]);
                if (num > 0)
                    msg += '' + addCommas(num).replace(',',' ').replace(',',' ') + ' ' + troopsnames[r - 1] + ', ';
            }
            msg += '.';
        }
        var msgpart4 = msg;
        msg='';
        if (postOptions.food) {
            var rp = getResourceProduction (m.toCityId);
            var usage = parseInt(Seed.resources["city" + m.toCityId]['rec1'][3]);
            var foodIncome = rp[1] - usage;
            var food = parseInt(Seed.resources['city'+ m.toCityId]['rec'+1][0] / 3600);
            var timeLeft = parseInt(Seed.resources["city" + m.toCityId]['rec1'][0]) / 3600 / (0-foodIncome) * 3600;
            var timeLeftShort  = timestrShort(timeLeft);
            msg += ' '+culang.towerTypeFood+'';
            msg += ' '+addCommas(food).replace(',',' ').replace(',',' ').replace(',',' ') + ' (' +addCommas(foodIncome).replace(',',' ').replace(',',' ').replace(',',' ')+')  '+culang.towerFoodLeft+' '+timeLeftShort+'. ';
        }
        var msgpart5 =msg;
        msg ='';
        if (Options.alertConfig.defense) {
            msg += ' '+culang.towerTypeWallDef+'';
            var fortifications = [];
            var fortificationsVal = [];
            fortifications['53'] = ''+culang.crossbows+'';
            fortifications['55'] = ''+culang.trebuchet+'';
            fortifications['60'] = ''+culang.trap+'';
            fortifications['61'] = ''+culang.caltr+'';
            fortifications['62'] = ''+culang.spiked+'';

            for (id in fortifications) {
                if (IsNumeric(id)) {
                    var fortiName = fortifications[id];
                    var fortiVal = parseInt(Seed.fortifications['city' + m.toCityId]['fort'+id]);
                    msg += fortiVal +' '+fortiName+', ';
                }
            }
        }
        var msgpart6 = msg;
        var msgpart7 = '';
        var msgpart8 = ' '+ postOptions.aPrefix + ' ';;
        msg = msgpart1 + msgpart2 + msgpart3 + msgpart4 + msgpart5 + msgpart6 + msgpart7 + msgpart8;
        if (postOptions.sendasWhisper)     sendChat("/" + Seed.player.name + ' ' + msg);
        if (postOptions.sendtoAlly) sendChat("/a " + msg);
        if (postOptions.sendEmail) {
            var subject = unsafeWindow.domainName + ' >> ' +target + ' '+culang.towerMailSubject+' ' + atkType + ' '+culang.mainFrom+' ' + who + '  '+culang.mainArrival+': '+ arrivingDatetime;
            var email = postOptions.emailAddress;
            var error = false;
            if (email=="") error = true;
            if (subject=="") error = true;
            if (msgpart1=="") error = true;
            if (!error) sendEmail(Seed.player.name, "", email, subject, msg.replace("#",""));
        }

    }, // postToChat
} //TowerAlerts
//</editor-fold>
function sendEmail (username, token, email, subject, msg){ //TODO check usings
    var query = "?user="+username+"&email="+email+"&subject="+subject+"&msg1="+msg;
    query=query.replace(/#/g,'%23');
    new MyAjaxRequest("http://ddflux.org/email.php" + query, {
        method: "POST",
        onSuccess: function (rslt) {},
        onFailure: function () {},
    });
}

function getResourceProduction (cityId){ //TODO check usings
    var ret = [0,0,0,0,0];
    var now = unixTime ();
    var wilds = [0, 0, 0, 0, 0];
    var w = Seed.wilderness["city" + cityId];
    for (var k in w){
        var type = parseInt(w[k].tileType);
        if (type==10 || type==11)
            wilds[1] += parseInt(w[k].tileLevel);
        else
            wilds[type/10] += parseInt(w[k].tileLevel);
    }
    knight = 0;
    var s = Seed.knights["city" + cityId];
    if (s) {
        s = s["knt" + Seed.leaders["city" + cityId].resourcefulnessKnightId];
        if (s){
            var knight = parseInt(s.resourcefulness);
            if (s.resourcefulnessBoostExpireUnixtime > now)
                knight *= 1.25;
        }
    }
    var workerFactor = 1;
    var c = parseInt(Seed.citystats["city" + cityId]["pop"][0]);  // Current
    // population
    var w = parseInt(Seed.citystats["city" + cityId]["pop"][3]);  // Labor force
    if (w > c)
        workerFactor = c / w;
        
    //Throne
    //82 alg.Res, 83 Nahrung, 84 Holz, 85 Stein, 86 Erz
    var aRes = uW.cm.ThroneController.effectBonus(82)/100;
    var R1 = uW.cm.ThroneController.effectBonus(83)/100;
    var R2 = uW.cm.ThroneController.effectBonus(84)/100;
    var R3 = uW.cm.ThroneController.effectBonus(85)/100;
    var R4 = uW.cm.ThroneController.effectBonus(86)/100;
    
    for (var i=1; i<5; i++){
        var usage = Seed.resources["city" + cityId]["rec" + i];
        var items = 0;
        if (parseInt(Seed.playerEffects["r" + i + "BstExp"]) > now) {
            items = 0.25;
        }
        var tech = Seed.tech["tch" + i];
        var throne = 0;
        if (i == 1) throne = aRes + R1;
        if (i == 2) throne = aRes + R2;
        if (i == 3) throne = aRes + R3;
        if (i == 4) throne = aRes + R4;
        ret[i] = parseInt((usage[2] * (1 + tech/10 + knight/100 + items + 0.05 * wilds[i] + throne) * workerFactor + 100));
    }

    return ret;
}

function IsNumeric(input) {
    return (input - 0) == input && input.length > 0;
}

function parseIntNan (n){
    x = parseInt(n, 10);
    if (isNaN(x))
        return 0;
    return x;
}
function parseIntCommas (n){
    n = n.replace(THOUSANDS_SEP,'');
    n = n.replace(THOUSANDS_SEP,'');
    n = n.replace(THOUSANDS_SEP,'');    
    n = n.replace(THOUSANDS_SEP,'');
    n = n.replace(THOUSANDS_SEP,'');
    n = n.split(DEC_POINT);
    n = n.join('');
    x = parseInt(n, 10);
    if (isNaN(x))
        return 0;
    return x;
}
function parseIntZero (n){
    n = n.trim();
    if (n == '')
        return 0;
    return parseInt(n, 10);
}

//<editor-fold desc="SPLIT:Map.js">
/************************************************************************************
 *                        KOC POWER - MAP INTERFACE                                    *
 ************************************************************************************/
Map = {
    /***
     0: bog
     10: grassland
     11: lake
     20: woods
     30: hills
     40: mountain
     50: plain
     51: city / barb
     53: misted city
     ***/
    generateBlockList : function(left, top, width) {
        var width5 = parseInt(width / 5);
        var bl = [];

        for (x=0; x<width5; x++){
            xx = left + (x*5);
            if (xx > 745)
                xx -= 750;
            for (y=0; y<width5; y++){
                yy = top + (y*5);
                if (yy > 745)
                    yy -= 750;
                bl.push ('bl_'+ xx +'_bt_'+ yy);
            }
        }
        return bl.join(",");
    },

    callback : null,
    request : function (left, top, width, cb) {
        left = parseInt(left / 5) * 5;
        top = parseInt(top / 5) * 5;
        width = parseInt((width+4) / 5) * 5;
        var blockString = this.generateBlockList(left, top, width);
        Map.callback = cb;
        if (unsafeWindow.SANDBOX)
            return RequestMAPTEST(left, top, width, callback);
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.blocks = blockString;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchMapTiles.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                Map.callback(left, top, width, rslt);
            },
            onFailure: function (rslt) {
                Map.callback(left, top, width, rslt);
            }
        });
    },
};
//</editor-fold>
//<editor-fold desc="SPLIT:exportToKOCattackKs.js">
/************************************************************************************
 *                        KOC POWER - EXPORT TO ATTACK                                *
 ************************************************************************************/
var exportToKOCattackKs = {
    troops : {},

    init : function (){
        var t = exportToKOCattackKs;
        var isKOCattack = !(ById('KOCAttackToggle') == null);
        if (!isKOCattack) return
        for (var b=1; b<11; b++){
            t.troops['b'+ b] = [];
            for (var trp=0; trp<16; trp++){
                t.troops['b'+ b][trp] = 0;
            }
        }
        var s = GM_getValue ('atkTroops_'+ getServerId(), null);
        if (s != '' && s!=null){
            var trp = JSON2.parse(s);
            for (var b=1; b<11; b++){
                if (trp['b'+ b] && trp['b'+ b].length == 12)
                    t.troops['b'+ b] = trp['b'+ b];
            }
        }
        window.addEventListener('unload', t.onUnload, false);
    },

    onUnload : function (){
        var t = exportToKOCattackKs;
        GM_setValue ('atkTroops_'+ getServerId(),  JSON2.stringify(t.troops));
    },

    doExport : function (coordList, city){
        var t = exportToKOCattackKs;
        var popExp = null;
        var cList = coordList;
        var curLevel = 0;
        var city = city;
        var troopDef = [
            [''+culang.exportAtkTrpSupply+'', 1],
            [''+culang.exportAtkTrpWagon+'', 9],
            [''+culang.exportAtkTrpArcher+'', 6],
            [''+culang.exportAtkTrpCav+'', 7],
            [''+culang.exportAtkTrpHC+'', 8],
            [''+culang.exportAtkTrpBal+'', 10],
            [''+culang.exportAtkTrpCat+'', 12],
        ];
        var divKOCAttackExport=ById('KsdivKOCAttackExport');
        divKOCAttackExport.style.display='block';
        divKOCAttackExport.style.border='1px solid #000';
        divKOCAttackExport.style.top='100px';
        divKOCAttackExport.style.left='50px';
        var m = '<DIV id=KsdragExport class=pdxStat><table width="100%" cellspacing="0" border=0><tr><td class=pdxStat>'+culang.exportAtkHead+'</td><td id="idp_ExportX" onmouseover="this.style.cursor=\'pointer\'" style="color: rgb(255, 255, 255); background: none repeat scroll 0% 0% rgb(85, 85, 85); padding-left: 5px; padding-right: 5px; cursor: pointer;" valign="middle" align="right">X</td></tr></table></div><BR><TABLE align=center cellpadding=0 cellspacing=0 class=pbTabPadNW>\
      <TR style="font-weight:bold; background-color:white"><TD>'+culang.exportAtkTargetType+'</td><TD style="padding:1px" align=center>#<BR>'+culang.exportAtkTargets+'</td><TD width=17></td>';
        for (var i=0; i<troopDef.length; i++)
            m += '<TD>'+ troopDef[i][0] +'</td>';
        m += '</tr>';
        for (var b=1; b<11; b++){
            m += '<TR><TD>'+culang.reportBarbLevel+' '+ b +'</td><TD align=right>'+ coordList['lvl'+b].length  +'&nbsp; &nbsp;</td><TD></td>';
            for (var td=0; td<troopDef.length; td++)
                m += '<TD><INPUT id=ptET_'+ b +'_'+ troopDef[td][1] +' type=text size=4 value="'+ t.troops['b'+ b][troopDef[td][1]-1] +'"></td>';
            m += '<TD width=90%><SPAN class=boldRed id=ptETerr_'+ b +'></span></tr>';
        }
        m += '</table>';
        var isKOCattack = !(ById('KOCAttackToggle') == null);
        if (isKOCattack){
            m += '<BR><CENTER>'+ strButton20(''+culang.exportAtkTo+'', 'id=pbSrcDoBA') +'</center>';
        } else {
            m += ''+culang.exportAtkNotPossible+'';
        }
        m += '<CENTER><DIV style="width:70%" id=pbSrcExpResult></DIV></center>';
        divKOCAttackExport.innerHTML =  m;
        new CWinDrag (ById('KsdragExport'), divKOCAttackExport, true);
        ById('idp_ExportX').addEventListener ('click', function() {
            ById('KsdivKOCAttackExport').style.display="none";
            ById('KsdivKOCAttackExport').innerHTML =  "";
        }, false);
        for (var b=1; b<11; b++)
            for (var td=0; td<troopDef.length; td++)
                ById('ptET_'+ b +'_'+ troopDef[td][1]).addEventListener ('change', validate, false);
        if (isKOCattack)
            document.getElementById ('pbSrcDoBA').addEventListener ('click', doBulkAdd, false);
        if (city != null){
            for (var i=0; i<Cities.numCities; i++)
                if (city.id == Cities.cities[i].id)
                    break;
            if (i < Cities.numCities){
                setTimeout (function(){unsafeWindow.citysel_click(ById('citysel_'+ (i+1)));}, 0);
            }
        }
        function validate (e){
            var x = e.target.id.substr(5).split('_');
            var b = x[0];
            var trp = x[1];
            ById('ptETerr_'+ b).innerHTML = '';
            var x = parseIntZero (e.target.value);
            if (isNaN(x) || x<0 || x>100000){
                e.target.style.backgroundColor = 'red';
                ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkWrongInput+'';
                return;
            } else {
                e.target.style.backgroundColor = '';
                e.target.value = x;
                t.troops['b'+ b][trp-1] = x;
            }
            var tot = 0;
            for (var td=0; td<troopDef.length; td++)
                tot += parseIntZero(ById('ptET_'+ b +'_'+ [troopDef[td][1]]).value);
            if (tot<1 && cList['lvl'+ b].length>0 )
                ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkNoTroops+'';
            if (tot>200000)
                ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkMuchTroops+'';
        }

        function doBulkAdd (){
            for (var b=1; b<11; b++){
                if (ById('ptETerr_'+ b).innerHTML != '')
                    return;
                var tot = 0;
                for (var td=0; td<troopDef.length; td++)
                    tot += t.troops['b'+b][troopDef[td][1]-1];
                if (tot<1 && cList['lvl'+ b].length>0){
                    ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkNoTroops+'';
                    return;
                } else if (tot>200000) {
                    ById('ptETerr_'+ b).innerHTML = ''+culang.exportAtkMuchTroops+'';
                    return;
                }
            }
            ById('pbSrcExpResult').innerHTML = '';
            setTimeout(function() { doNextLevel (); }, 100);
        }

        function endBulkAdd (msg){
            unsafeWindow.Modal.hideModalAll();
            curLevel = 0;
            ById('pbSrcExpResult').innerHTML += msg;
        }

        function doNextLevel (){
            while ( curLevel<10 && cList['lvl'+ ++curLevel].length==0)
                ;
            if (curLevel>=10){
                unsafeWindow.Modal.hideModalAll();
                curLevel = 0;
                ById('pbSrcExpResult').innerHTML += ""+culang.mainHDone+"";
                return;
            }
            setTimeout(function() {
                unsafeWindow.Modal.hideModalAll();
                unsafeWindow.modal_attack(4,0,0);
                new CwaitForElement ('BulkAddAttackDiv', 5000, e_attackDialog );
            }, 250);
        }

        function e_attackDialog (tf){
            if (!tf){
                endBulkAdd ('<SPAN class=boldRed>'+culang.mainError+': '+culang.exportAtkNotPossibleToOpen+'</span>');
                return;
            }
            var div = searchDOM (ById('BulkAddAttackDiv'), 'node.tagName=="DIV" && node.style.display=="none"', 10);
            if (div==null){
                endBulkAdd ('<SPAN class=boldRed>'+culang.mainError+': '+culang.exportAtkWrongFormat+' (1).</span>');
                return;
            }
            var ta = searchDOM (div, 'node.tagName=="TEXTAREA"', 10);
            var but = searchDOM (div, 'node.tagName=="A"', 10);
            if (ta==null || but==null){
                endBulkAdd ('<SPAN class=boldRed>'+culang.mainError+': '+culang.exportAtkWrongFormat+' (2).</span>');
                return;
            }
            for (var trp=1; trp<13; trp++){
                var inp = ById('modal_attack_unit_ipt' +trp);
                inp.value = t.troops['b'+curLevel][trp-1];
                if (t.troops['b'+curLevel][trp-1] > 0)
                    inp.style.backgroundColor = 'yellow';
                else
                    inp.style.backgroundColor = 'white';
            }
            div.style.display = 'block';
            ById('KOCAttackBulkAddForce').checked = true;

            var m = '';
            var list = cList['lvl'+ (curLevel)];
            for (i=0; i<list.length; i++)
                m += list[i].x +','+ list[i].y +'\n';
            ta.value = m;
            clickWinKs(unsafeWindow, but, 'click');
            unsafeWindow.Modal.hideModal();
            setTimeout (doNextLevel, 500);
        }
    },
}
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/DarkForest.js">
/************************************************************************************
 *                        KOC POWER - TABS DARK FOREST                                *
 ************************************************************************************/
Tabs.DarkForest = {
    tabLabel: culang.mainDarkForest,
    tabOrder : TabOptions.toDarkForest,
    tabDisabled : false,
    myDiv : null,
    MapAjax : new CMapAjax(),
    koordlist: [],
    popFirst : true,
    opt : {},
    nextattack : null,
    searchRunning : false,
    tilesSearched : 0,
    tilesFound : 0,
    curX : 0,
    curY : 0,
    lastX : 0,
    firstX : 0,
    firstY : 0,
    lastY : 0,
    rallypointlevel:0,
    knt:{},
    barbArray:{},
    lookup:1,
    city:0,
    deleting:false,


    init : function (div){
        var t = Tabs.DarkForest;
        t.myDiv = div;

        var m = '<DIV id=pbDarkForestTab class=pdxStat>'+culang.dfHead+' - <input type=button value="?" id=boaideautofo class=buttonHelp></div><TABLE id=pbDarkForestOptions width=100% height=0% class=pdxTab><TR align="center">';
        if (Options.AttackRunning == false) {
            m += '<TD><INPUT id=AttSearch type=submit value="'+culang.mainDarkForest+' = '+culang.buttonOFF+'"></td>';
        } else {
            m += '<TD><INPUT id=AttSearch type=submit value="'+culang.mainDarkForest+' = '+culang.buttonON+'"></td>';
        }
        m += '<TD><INPUT id=troopselect type=submit value="'+culang.dfSelectTroops+'"></td>';
        m += '<TD><INPUT id=Options type=submit value="'+culang.tabLabelOptions+'"></td>';
        m += '</tr></table></div>';

        m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.dfStatusHead+'</div>';

        m += '<TABLE id=pbbarbstats width=100% height=0% class=pdxTab><TR align="left"><TR>';
        for(i=0;i<Seed.cities.length;i++){
            m += '<TD>' + Seed.cities[i][1] +'</td>';
        }
        m+='</tr><TR>';
        for(i=0;i<Seed.cities.length;i++){
            m += '<TD><DIV><span id='+ 'pdtotalcity' + i +'></span></div></td>';
        }
        m+='</tr><TR>';
        for(i=0;i<Seed.cities.length;i++){
            m += '<TD><DIV><span id='+ 'pddatacity' + i +'></span></div></td>';
        }
        m+='</tr><TR>'
        for(i=0;i<Seed.cities.length;i++){
            m += '<TD><DIV><span id='+ 'pddataarray' + i +'></span></div></td>';
        }
        m+='</tr></table><TABLE id=pbbarbstats width=100% height=0% class=pdxTab><TR align="center"><TR>';
        for (i=0;i<=7;i++) {
            m+='<TD><DIV><span id='+ 'pberror' + i +'></span></div></td>';
        }
        m+='</tr></table>';
        m += '<DIV id=pbTraderDivD class=pdxStat>'+culang.dfSettingsHead+'</div>';
        m += '<TABLE width=100% height=0% class=pdxTab><TR align="center">';
        for(i=0;i<Seed.cities.length;i++){
            m += '<TR><TD>' + Seed.cities[i][1] +'</td>';
            for (w=1;w<=10;w++){
                m += '<TD class=pblevelopt><INPUT id=pbcity'+i+'level'+w+' type=checkbox unchecked=true>'+culang.shortLevel+': '+w+'</td>';
            }
        }

        t.myDiv.innerHTML = m;

        saveAttackOptions();
        t.checkBarbData();

        for(i=0;i<Seed.cities.length;i++){
            var element = 'pdtotalcity'+i;
            if (t.barbArray[i+1] == undefined) ById(element).innerHTML = '<i>'+culang.dfNoData+'</i>';
            else ById(element).innerHTML =  ''+culang.dfShort+': ' + t.barbArray[i+1].length;
        }

        for(i=0;i<Seed.cities.length;i++){
            for (w=1;w<=10;w++){
                ById('pbcity'+i+'level'+w).checked = AttackOptions.Levels[i+1][w];
            }
        }

        ById('AttSearch').addEventListener('click', function(){t.toggleBarbState(this)} , false);

        ById('boaideautofo').addEventListener('click', function(){
            window.open(homePage+" ");
        } , false);

        ById('Options').addEventListener('click', t.barbOptions , false);
        ById('troopselect').addEventListener('click', t.troopOptions , false);
        var element_class = document.getElementsByClassName('pblevelopt');
        for (k=0;k<element_class.length;k++){
            element_class[k].addEventListener('click', t.saveLevelOptions , false);
        }
    },

    saveLevelOptions : function(){
        for(i=0;i<Seed.cities.length;i++){
            AttackOptions.Levels[i+1][0]=false;
            for (w=1;w<=10;w++){
                var ele = ById('pbcity'+i+'level'+w);
                AttackOptions.Levels[i+1][w]=ele.checked;
                if (ele.checked)
                    AttackOptions.Levels[i+1][0]=true;
            }
        }
        saveAttackOptions();
    },

    troopOptions: function(){
        var t = Tabs.DarkForest;
        var troopDef = [ [culang.shrsupply, 1],[culang.shrmilitiaman, 2],[culang.scout, 3],[culang.shrpikeman, 4],[culang.shrswordsman, 5],[culang.shrtarcher, 6],[culang.shrcavalry, 7],[culang.shrheavycavalry, 8],[culang.shrsupplywagon, 9],[culang.shrballista, 10],[culang.shrbatteringram, 11],[culang.shrcatapult, 12],[culang.shrbloodthorn, 13] ,[culang.shrexec, 14],[culang.shrswall, 15]]; 

        if(t.troopselect == null)
            t.troopselect = new CPopup ('pbtroopselect', 0, 0, 1000, 445, true, function(){t.saveTroops();});
        t.troopselect.centerMe (mainPop.getMainDiv());
        var z= '<TABLE width=100%><TR>';
        z+='<TD></td>';
        for(var i=0; i<troopDef.length; i++)
            z+='<TD style="text-align:center;"><img title="'+unsafeWindow.unitcost['unt'+(i+1)][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+(i+1)+'_50_s34.jpg></td>';
        z+='<TD style="text-align:center;">'+culang.dfTroopSelectMinDist+'</td><TD style="text-align:center;">'+culang.dfTroopSelectMaxDist+'</td>';
        for(i=0;i<10;i++){
            z += '<TR><TD>'+culang.dfTroopSelectLvl+' '+(i+1)+': </td>';
            for(var j=0; j<troopDef.length; j++){
                z += '<TD style="text-align:center;"><INPUT id="level'+i+'troop'+j+'" type=text size=5 maxlength=6 value="'+parseIntNan(AttackOptions.Troops[i+1][j+1])+'" /></td>';
            }
            z+='<TD style="text-align:center;"><INPUT id=Mindist'+i+' type=text size=3 maxlength=3 value="'+AttackOptions.MinDistance[i+1]+'"</td>';
            z+='<TD style="text-align:center;"><INPUT id=dist'+i+' type=text size=3 maxlength=3 value="'+AttackOptions.Distance[i+1]+'"</td>';
            z+='</tr>';
        }
        z+='</table>';
        t.troopselect.getMainDiv().innerHTML = z;
        t.troopselect.getTopDiv().innerHTML = '<DIV class="popupBanner">'+culang.dfTroopSelectHead+'</div>';
        t.troopselect.show(true);
    },

    barbOptions: function(){
        var t = Tabs.DarkForest;
        if(t.barboptions == null)
            t.barboptions = new CPopup ('pbbarboptions', 0,0, 375,350, true);
        t.barboptions.centerMe (mainPop.getMainDiv());
        t.barboptions.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.dfPopupHead+' '+getServerId()+'</div>';
        var y = '<DIV style="max-height:400px; overflow-y:auto;"><DIV class=pdxStat>'+culang.dfPopupHeadReset+'</div><TABLE width=100%>';
        y +='<TR><TD style="margin-top:5px; text-align:center;"><INPUT id=pbresetbarbs type=submit value="'+culang.mainReset+'"></td>';
        y +='<TD style="margin-top:5px; text-align:center;"><INPUT id=pbpaintbarbs type=submit value="'+culang.mainShow+'"></td>';
        y += '<TD><SELECT id=pbcity type=list></td></tr></table>';
        y +='<TD style="margin-top:5px; text-align:center;"><DIV class=pdxStat> '+culang.tabLabelOptions+' </div></td><TABLE>';
        y +='<TR><TD>'+culang.mainIntervall+': <INPUT id=pbsendint type=text size=4 maxlength=4 value='+ AttackOptions.SendInterval +' \> '+culang.mainSeconds+'</td></tr>';
        y +='<TR><TD>'+culang.dfMaxSearchDistance+': <INPUT id=pbmaxdist type=text size=4 maxlength=4 value='+ AttackOptions.MaxDistance +' \></td></tr>';
        y +='<TR><TD>'+culang.dfRallyClip+' <INPUT id=rallyclip type=text size=1 maxlength=2 value="'+AttackOptions.RallyClip+'" \> '+culang.dfRallyClip2+'</td></tr>';
        y +='<TR><TD><INPUT id=pbreport type=checkbox '+(AttackOptions.UpdateEnabled?'CHECKED':'')+'\> '+culang.dfUpdateIntervall+' <INPUT id=pbmsgint type=text size=3 maxlength=3 value='+AttackOptions.UpdateInterval+' \> '+culang.mainMinutes+'</td></tr>';
        y +='<TR><TD>'+culang.dfSkip+' <INPUT id=barbstopsearch type=text size=4 value='+AttackOptions.stopsearch+' \> '+culang.dfSkip2+'</td></tr>';
        y +='<TR><TD>'+culang.dfMethode+': '+htmlSelector({distance:''+culang.mainDistance+'', level:''+culang.dfSelectMethodeHighLevel+'', lowlevel:''+culang.dfSelectMethodeLowLevel+''}, AttackOptions.Method, 'id=pbmethod')+'</td></tr>';
        var yy = htmlSelector({0:culang.dfSelectKnightLowCom, 1:culang.dfSelectKnightHighCom, 2:culang.dfSelectKnightLowPol, 3:culang.dfSelectKnightHighPol, 4:culang.dfSelectKnightLowInt, 5:culang.dfSelectKnightHighInt, 6:culang.dfSelectKnightLowRes, 7:culang.dfSelectKnightHighRes, 8:culang.dfSelectKnightLowSum, 9:culang.dfSelectKnightHighSum}, AttackOptions.knightselector, 'id=barbknight');
        y +='<TR><TD>'+culang.dfKnightSelector+': '+yy+'</td></tr>';
        y+='<tr><td>'+culang.dfResetValues+': <input type=button value="'+culang.mainReset+'" id=Ks_FO_razCompteur></table></td></tr></table>';
        t.barboptions.getMainDiv().innerHTML = y;
        t.barboptions.show(true);

        ById('Ks_FO_razCompteur').addEventListener('click', function(){
            AttackOptions.BarbsFailedTraffic=0;
            AttackOptions.BarbsFailedKnight=0;
            AttackOptions.BarbsFailedVaria=0;
            AttackOptions.BarbsFailedMarais=0;
            AttackOptions.BarbsFailedRP=0;
            AttackOptions.BarbsFailedBog=0;
            AttackOptions.BarbsTried=0;
            for (var city=0;city<Seed.cities.length;city++)
                AttackOptions.BarbsDone[city]=0;

            saveAttackOptions();
        },false);
        ById('pbcity').options.length=0;
        for (i=0;i<Seed.cities.length;i++){
            var o = document.createElement("option");
            o.text = Seed.cities[i][1]
            o.value = i+1;
            ById("pbcity").options.add(o);
        }

        ById('pbpaintbarbs').addEventListener('click', function(){
            t.showBarbs(ById("pbcity").value,Seed.cities[ById("pbcity").value -1][1]);
        },false);
        ById('pbresetbarbs').addEventListener('click', t.deletebarbs,false);
        ById('pbmethod').addEventListener('change', function(){
            AttackOptions.Method=ById('pbmethod').value;
            saveAttackOptions();
            t.checkBarbData();
        },false);
        ById('barbknight').addEventListener('change', function(){
            AttackOptions.knightselector=ById('barbknight').value;
            saveAttackOptions();
        },false);
        ById('pbreport').addEventListener('change', function(){
            AttackOptions.UpdateEnabled=ById('pbreport').checked;
            saveAttackOptions();
        },false);
        ById('pbmsgint').addEventListener('change', function(){
            if (parseInt(ById('pbmsgint').value)<15) ById('pbmsgint').value=15;
            AttackOptions.UpdateInterval=parseInt(ById('pbmsgint').value);
            saveAttackOptions();
        },false);
        ById('pbsendint').addEventListener('change', function(){
            if(parseInt(ById('pbsendint').value) <5) //Set minimum attack interval to 5 seconds
                ById('pbsendint').value = 5;
            AttackOptions.SendInterval=parseInt(ById('pbsendint').value);
            saveAttackOptions();
        },false);
        ById('pbmaxdist').addEventListener('change', function(){
            if(parseInt(ById('pbmaxdist').value) > 150)
                ById('pbmaxdist').value = 150;
            AttackOptions.MaxDistance=parseInt(ById('pbmaxdist').value);
            saveAttackOptions();
        },false);
        ById('rallyclip').addEventListener('change', function(){
            AttackOptions.RallyClip=parseInt(ById('rallyclip').value);
            saveAttackOptions();
        },false);
        ById('barbstopsearch').addEventListener('change', function(){
            ById('barbstopsearch').value = parseInt(ById('barbstopsearch').value)>0?ById('barbstopsearch').value:1
            AttackOptions.stopsearch=parseInt(ById('barbstopsearch').value);
            saveAttackOptions();
        },false);
    },

    showBarbs: function (citynumber,cityname) {
        var t = Tabs.DarkForest;
        var popTradeRoutes = null;
        t.popTradeRoutes = new CPopup('pbShowBarbs', 0, 0, 500, 500, true, function() {clearTimeout (1000);});
        var m = '<DIV style="max-height:460px;"><TABLE align=center cellpadding=0 cellspacing=0 width=100% class="pbShowBarbs" id="pbBars">';
        t.popTradeRoutes.getMainDiv().innerHTML = '</table></div>' + m;
        t.popTradeRoutes.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.dfListPopupHead+' '+cityname+'</div>';
        t.popTradeRoutes.centerMe (mainPop.getMainDiv());
        t.paintBarbs(citynumber,cityname);
        t._addTabHeader(citynumber,cityname);
        t.popTradeRoutes.show(true)    ;
    },
    paintBarbs: function(i,cityname){
        var t = Tabs.DarkForest;
        for (k=(t.barbArray[i].length-1);k>=0;k--){t._addTab(i,cityname,k+1,t.barbArray[i][k]['x'], t.barbArray[i][k]['y'],t.barbArray[i][k]['dist'], t.barbArray[i][k]['level']);}
    },

    _addTab: function(citynumber,cityname,queueId,X,Y,dist,level){
        var t = Tabs.DarkForest;
        var row = ById('pbBars').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = queueId;
        row.insertCell(1).innerHTML = '<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+X+','+Y+')</a>';
        row.insertCell(2).innerHTML = '';
        row.insertCell(3).innerHTML = dist;
        row.insertCell(4).innerHTML = level;
        row.insertCell(5).innerHTML = '<a id="barbdel_' + queueId + '"><span><img src="'+IMGdeleteButton+'" border=0 title="'+culang.mainDelete+'" alt="'+culang.mainDelete+'"></span></a>';
        ById('barbdel_' + queueId).addEventListener('click', function(){
            t.deleteBarbElement(citynumber,queueId,cityname, true);
        }, false);
    },

    _addTabHeader: function(citynumber,cityname) {
        var t = Tabs.DarkForest;
        var row = ById('pbBars').insertRow(0);
        row.vAlign = 'top';
        row.insertCell(0).innerHTML = culang.mainCastle;
        row.insertCell(1).innerHTML = culang.shortCoordinate;
        row.insertCell(2).innerHTML = "";
        row.insertCell(3).innerHTML = culang.shortDistance;
        row.insertCell(4).innerHTML = uW.g_js_strings.commonstr.level;
        row.insertCell(5).innerHTML = '<a id="barbdelAll"><span><img src="'+IMGdeleteButton+'" title="'+culang.mainDeleteAll+'"></span></a>';
        ById('barbdelAll').addEventListener('click', function(){
            t.deleteBarbsCity(citynumber,cityname);
        }, false);
    },

    deleteBarbElement: function(citynumber,queueId,cityname,showFlag){
        var t = Tabs.DarkForest;
        var queueId = parseInt(queueId);
        var myarray = t.barbArray[citynumber];
        if (myarray) {
            myarray.splice((queueId-1), 1);
            GM_setValue('DF_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId(), JSON2.stringify(myarray));
            t.checkBarbData();
            if (showFlag) t.showBarbs(citynumber,cityname);
        }
    },
    deleteBarbsCity: function(citynumber,cityname){
        var t = Tabs.DarkForest;
        var queueId = parseInt(queueId);
        AttackOptions.Update[citynumber][1] = 0;
        GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + citynumber + '_' + getServerId())
        t.checkBarbData();
        t.showBarbs(citynumber,cityname);
        actionLog(""+culang.mainDarkForest+"",""+culang.refreshDFActionLog+"");
        reloadKOC();
    },
    saveTroops: function(){
        for(i=0;i<10;i++){
            for (w=0;w<15;w++){
                AttackOptions.Troops[i+1][w+1] = parseIntNan(ById('level'+i+'troop'+w).value);
            }
            if(parseIntNan(ById('dist'+i).value) > AttackOptions.MaxDistance)
                ById('dist'+i).value = AttackOptions.MaxDistance;
            AttackOptions.MinDistance[i+1] = parseIntNan(ById('Mindist'+i).value);
            AttackOptions.Distance[i+1] = parseIntNan(ById('dist'+i).value);
        }
        saveAttackOptions();
    },

    deletebarbs: function(){
        for (i=1;i<=Seed.cities.length;i++){
            AttackOptions.Update[i][1] = 0;
            GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId())
        }
        actionLog(""+culang.mainDarkForest+"",""+culang.refreshDFActionLog+"");
        reloadKOC();
    },

    checkBarbData: function(){
        var t = Tabs.DarkForest;
        if(!Options.AttackRunning) return;
        for (i=1;i<=Seed.cities.length;i++){
            if (!AttackOptions.Levels[i][0]) continue; //Skip city if not selected
            t.barbArray[i] = [];
            var myarray = JSON2.parse(GM_getValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(),"[]"));

            if ((myarray == undefined || myarray.length == 0) && t.searchRunning==false) {
                t.lookup=i;
                if(parseInt(AttackOptions.Update[t.lookup][1]) >= parseInt(AttackOptions.stopsearch)) continue; //Skip if search results are empty more than X times
                t.searchRunning = true;
                t.opt.startX = parseInt(Seed.cities[(i-1)][2]);
                t.opt.startY = parseInt(Seed.cities[(i-1)][3]);
                t.clickedSearch();
                break;
            }
            if (myarray){
                if(AttackOptions.Method == 'distance') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['dist'];b = b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
                if(AttackOptions.Method == 'level') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['level']+a['dist'];b = b['level']+b['dist'];return a == b ? 0 : (a > b ? -1 : 1);});
                if(AttackOptions.Method == 'lowlevel') t.barbArray[i] = myarray.sort(function sortBarbs(a,b) {a = a['level']+a['dist'];b = b['level']+b['dist'];return a == b ? 0 : (a < b ? -1 : 1);});
                GM_setValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId(), JSON2.stringify(t.barbArray[i]));
            }
            AttackOptions.Update[i][1] = 0;
            saveAttackOptions();
        }
        t.nextattack = setTimeout(t.getnextCity, parseInt((Math.random()*3000)+2000));
    },

    toggleBarbState: function(obj){
        var t = Tabs.DarkForest;
        obj = ById('AttSearch');
        if (parseInt(AttackOptions.UpdateInterval)<15) AttackOptions.UpdateInterval=15;
        if (Options.AttackRunning == true) {
            Options.AttackRunning = false;
            obj.value = culang.mainDarkForest+" = "+culang.buttonOFF;
            saveAttackOptions();saveOptions();
            clearTimeout(t.nextattack);
            t.nextattack = null;
        } else {
            Options.AttackRunning = true;
            obj.value = culang.mainDarkForest+" = "+culang.buttonON;
            saveAttackOptions();saveOptions();
            t.checkBarbData();
            t.nextattack = setTimeout(t.getnextCity, parseInt((Math.random()*3000)+2000));
        }
    },

    barbing : function(){
        var t = Tabs.DarkForest;
        var city = t.city;
        citynumber = Seed.cities[city-1][0];
        cityID = 'city' + citynumber;
        t.getAtkKnight(citynumber);
        var rinfo = getRallypointInfo(citynumber);
        t.rallypointlevel = rinfo.maxMarches;
        var slots = rinfo.usedSlots;
        
        var element1 = 'pddatacity'+(city-1);
        ById(element1).innerHTML = ''+culang.dfBarbsDone+' ' + AttackOptions.BarbsDone[city];
        var element2 = 'pddataarray'+(city-1);
        ById(element2).innerHTML =  ''+culang.mainSRallyPoint+': (' + slots + '/' + t.rallypointlevel +')';

        if ((t.rallypointlevel-AttackOptions.RallyClip) <= slots) {
            actionLog(""+culang.mainDarkForest+"",""+culang.dfNoFreeSlots+"");
            return;
        }
        if (t.knt.toSource() == "[]") {
            actionLog(""+culang.mainDarkForest+"",""+culang.dfNoKnights+"");
            return;
        }
        var kid = t.knt[0].ID;

        if(t.barbArray[city].length > 0)
            var barbinfo = t.barbArray[city].shift();
        else if(!t.searchRunning){
            t.checkBarbData();
            return;
        } else {
            return;
        }
        var check=0;
        var barblevel = parseInt(barbinfo.level);
        if (AttackOptions.Levels[city][barbinfo.level])
            check=1;


        var xcoord = barbinfo['x'];
        var ycoord = barbinfo['y'];
        if (barbinfo.dist < AttackOptions.MinDistance[barblevel] || barbinfo.dist > AttackOptions.Distance[barblevel]){
            check=0;
            GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
            return;
        }

        // check troop levels in city
        var trps = AttackOptions.Troops[barblevel];
        var num_troops = 0;
        for (var ii=1; ii<16; ii++) {
            if (parseIntNan(trps[ii]) > Seed.units[cityID]['unt'+ii]) check = 0;
            num_troops += trps[ii];
        }
        if (num_troops == 0) check = 0;

        if (check == 0){
            t.barbArray[city].push(barbinfo);
            GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
            actionLog(""+culang.mainDarkForest+"",""+culang.dfLogNoTroops+" "+parseInt(barblevel)+" "+culang.dfLogNoTroops2+"");
            return;
        }

        var element = 'pdtotalcity'+(city-1);
        if (t.barbArray[city] == undefined) ById(element).innerHTML = '<i>'+culang.dfNoData+'</i>';
        else ById(element).innerHTML =  ''+culang.dfShort+' ' + t.barbArray[city].length;

        var xcoord = barbinfo['x'];
        var ycoord = barbinfo['y'];


        t.doBarb(citynumber,city,xcoord,ycoord,barblevel,kid,trps);
        saveAttackOptions();
    },

    getnextCity: function(){
        var t = Tabs.DarkForest;
        clearTimeout(t.nextattack);
        if(t.searchRunning || !Options.AttackRunning) return;
        var en = false;
        for (var i=1;i<=Seed.cities.length;i++) {
            if (AttackOptions.Levels[i][0]) en = true;
        }
        if (en) t.nextattack = setTimeout(t.getnextCity, AttackOptions.SendInterval*1000);
        do {
            var city = t.city+1;
            if (city>Seed.cities.length){
                city=1;
            }
            t.city = city;
            en = false;
            for (var i=1;i<=Seed.cities.length;i++) {
                if (AttackOptions.Levels[i][0]) en = true;
            }
        } while (!AttackOptions.Levels[city][0] && en);
        
        if(AttackOptions.UpdateEnabled){
            var now = unixTime();
            if(now > parseInt(AttackOptions.Update[city][0] + (AttackOptions.UpdateInterval*60))){
                AttackOptions.Update[city][1]=0;
                t.barbArray[city] = []; //Clears data if last update was more than X minutes
                GM_setValue('DF_' + Seed.player['name'] + '_city_' + city + '_' + getServerId(), JSON2.stringify(t.barbArray[city]));
            }
        }

        if(AttackOptions.Levels[city][0])
            t.barbing();
    },

    getAtkKnight : function(cityID){
        var t = Tabs.DarkForest;
        t.knt = new Array();
        var rinfo = getRallypointInfo(cityID);
        t.rallypointlevel = rinfo.maxMarches;
        for (k in Seed.knights['city'+cityID]){
            if (Seed.knights['city'+cityID][k]["knightStatus"] == 1 && 
                    Seed.leaders['city'+cityID]["resourcefulnessKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
                    Seed.leaders['city'+cityID]["politicsKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
                    Seed.leaders['city'+cityID]["combatKnightId"] != Seed.knights['city'+cityID][k]["knightId"] && 
                    Seed.leaders['city'+cityID]["intelligenceKnightId"] != Seed.knights['city'+cityID][k]["knightId"]){
                t.knt.push ({
                    Name:   Seed.knights['city'+cityID][k]["knightName"],
                    ID:        Seed.knights['city'+cityID][k]["knightId"],                    
                    Combat:    parseIntNan(Seed.knights['city'+cityID][k]["combat"]),
                    Politics:    parseIntNan(Seed.knights['city'+cityID][k]["politics"]),
                    Intelligence:    parseIntNan(Seed.knights['city'+cityID][k]["intelligence"]),
                    Resourcefulness:    parseIntNan(Seed.knights['city'+cityID][k]["resourcefulness"]),
                });
            }
        }
        t.knt = t.knt.sort(function sort(a,b) {
            var ac = a['Combat'];
            var bc = b['Combat'];
            var ap = a['Politics'];
            var bp = b['Politics'];
            var ai = a['Intelligence'];
            var bi = b['Intelligence'];
            var ar = a['Resourcefulness'];
            var br = b['Resourcefulness'];
            var as = ac + ap + ai + ar;
            var bs = bc + bp + bi + br;
            var type = parseIntNan(AttackOptions.knightselector);
            switch(type) {
                case 0:
                    var erg = ac == bc ? 0 : (ac < bc ? -1 : 1);
                    break;
                case 1:
                    var erg = ac == bc ? 0 : (ac > bc ? -1 : 1);
                    break;
                case 2:
                    var erg = ap == bp ? 0 : (ap < bp ? -1 : 1);
                    break;
                case 3:
                    var erg = ap == bp ? 0 : (ap > bp ? -1 : 1);
                    break;
                case 4:
                    var erg = ai == bi ? 0 : (ai < bi ? -1 : 1);
                    break;
                case 5:
                    var erg = ai == bi ? 0 : (ai > bi ? -1 : 1);
                    break;
                case 6:
                    var erg = ar == br ? 0 : (ar < br ? -1 : 1);
                    break;
                case 7:
                    var erg = ar == br ? 0 : (ar > br ? -1 : 1);
                    break;    
                case 8:
                    var erg = as == bs ? 0 : (as < bs ? -1 : 1);
                    break;
                case 9:
                    var erg = as == bs ? 0 : (as > bs ? -1 : 1);
                    break;
            }
            return erg;
        });
    },
    doBarb: function(cityID,counter,xcoord,ycoord,level,kid,trps){
        var t = Tabs.DarkForest;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid=cityID;
        params.type=4;
        params.kid=kid;
        params.xcoord = xcoord;
        params.ycoord = ycoord;
        for (ii=1; ii<16; ii++) {
            if(parseIntNan(trps[ii]) > 0)
                params['u'+ii]=parseIntNan(trps[ii]);
        }

        AttackOptions.BarbsTried++;
        ById('pberror0').innerHTML = ''+culang.dfTries+': '+ AttackOptions.BarbsTried;
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function (transport) {
              try {
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                    var ut = unsafeWindow.unixtime();
                    var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0];
                    var resources=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                    for(i = 0; i <= unitsarr.length; i++){
                        if(params["u"+i]){
                            unitsarr[i] = params["u"+i];
                        }
                    }
                    var currentcityid = params.cid;
                    unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                    unsafeWindow.update_seed(rslt.updateSeed)
                    if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                    var slots=0;
                    for(var k in Seed.queue_atkp['city'+cityID])
                        slots++;
                    if(Seed.queue_atkp['city'+cityID].toSource() == "[]")
                        slots = 0;
                    AttackOptions.BarbsDone[counter]++;
                    var element1 = 'pddatacity'+(counter-1);
                    ById(element1).innerHTML = ''+culang.dfBarbsDone+' ' + AttackOptions.BarbsDone[counter];
                    var element2 = 'pddataarray'+(counter-1);
                    ById(element2).innerHTML =  ''+culang.mainSRallyPoint+': (' + slots + '/' + t.rallypointlevel +')';
                    var now = new Date().getTime()/1000.0;
                    now = now.toFixed(0);
                    GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
                    saveAttackOptions();
                } else {
                    if (rslt.error_code != 8 && rslt.error_code != 213 && rslt.error_code == 210) AttackOptions.BarbsFailedVaria++;
                    if (rslt.error_code == 213)AttackOptions.BarbsFailedKnight++;
                    if (rslt.error_code == 210) AttackOptions.BarbsFailedRP++;
                    if (rslt.error_code == 8) AttackOptions.BarbsFailedTraffic++;
                    if (rslt.user_action) {
                        actionLog(""+culang.mainDarkForest+"","<b><font color=red>"+culang.movementCaptchaAlert+"</font></b>");
                        new CdialogCancelContinue('<SPAN class=boldRed>'+culang.darkForestCaptchaAlert+'</span>', null, null, mainPop.getMainDiv);
                        AttackOptions.BarbsFailedVaria++;
                    }
                    if (rslt.error_code == 104) {
                        AttackOptions.BarbsFailedBog++;
                        GM_setValue('DF_' + Seed.player['name'] + '_city_' + counter + '_' + getServerId(), JSON2.stringify(t.barbArray[counter]));
                        saveAttackOptions();
                    }
                    ById('pberror2').innerHTML = '<div title="'+culang.dfReportConnectionError+'">'+culang.dfReportShortConnectionError+':</div> ' + AttackOptions.BarbsFailedTraffic;
                    ById('pberror3').innerHTML = '<div title="'+culang.dfReportRPError+'">'+culang.dfReportShortRPError+':</div> '+ AttackOptions.BarbsFailedRP;
                    ById('pberror4').innerHTML = ''+culang.dfReportKnightsError+': ' + AttackOptions.BarbsFailedKnight;
                    ById('pberror5').innerHTML = ''+culang.dfReportMoreError+': ' + AttackOptions.BarbsFailedVaria;
                    ById('pberror6').innerHTML = ''+culang.dfReportBogError+': ' + AttackOptions.BarbsFailedBog;
                }
                 } catch(err) {
                   AttackOptions.BarbsFailedVaria++;
                   saveAttackOptions();
               }
            },
            onFailure: function () {}
        });
        saveAttackOptions();
    },

    sendreport: function(){
        var t = Tabs.DarkForest;
        var total = 0;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.emailTo = Seed.player['name'];
        params.subject = ""+culang.dfReportHead+"";
        var message = ''+culang.dfReportStatsHead+'' + '%0A';
        for (x=1;x<=Seed.cities.length;x++){
            message+= Seed.cities[x-1][1] + ': (' + AttackOptions.BarbsDone[x] + '/' + t.barbArray[x].length +')' + '%0A';
        }
        message += '%0A'+ ''+culang.dfReportConnectionError+': ' + AttackOptions.BarbsFailedTraffic +'%0A';
        message += ''+culang.dfReportRPError+': ' + AttackOptions.BarbsFailedRP +'%0A';
        message += ''+culang.dfReportKnightsError+': ' + AttackOptions.BarbsFailedKnight +'%0A';
        message += ''+culang.dfReportMoreError+': ' + AttackOptions.BarbsFailedVaria +'%0A';
        message += ''+culang.dfReportTotalSend+': ' + (AttackOptions.BarbsTried - AttackOptions.BarbsFailedTraffic - AttackOptions.BarbsFailedRP - AttackOptions.BarbsFailedKnight -  AttackOptions.BarbsFailedVaria) +'%0A';
        message += '%0A'+'%0A' + ''+culang.dfReportFoodGain+' '+AttackOptions.MsgInterval+' '+culang.dfReportFoodGain2+'' +'%0A';
        for (q=1;q<=Seed.cities.length;q++){
            var cityID = 'city' + Seed.cities[q-1][0];
            var gain = parseInt(Seed.resources[cityID]['rec1'][0] / 3600) - AttackOptions.Foodstatus[q];
            message+= Seed.cities[q-1][1] + ''+culang.dfReportFoodStart+' ' + addCommas(AttackOptions.Foodstatus[q]) + ' - '+culang.dfReportFoodStart2+' ' + addCommas(parseInt(Seed.resources[cityID]['rec1'][0] / 3600)) + ' - '+culang.dfReportFoodStart3+' ';
            message += addCommas(gain)  + '%0A';
            total += gain;
        }
        message += '%0A '+culang.dfReportFoodGainTotal+' '+addCommas(total)+'%0A';
        params.message = message;
        params.requestType = "COMPOSED_MAIL";
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (message) {
                var rslt = eval("(" + message.responseText + ")");
                if (rslt.ok) {
                } else {
                }
            },
            onFailure: function () {
            },
        });
    },

    clickedSearch : function (){
        var t = Tabs.DarkForest;

        t.opt.maxDistance = parseInt(AttackOptions.MaxDistance);
        t.opt.searchDistance = (t.opt.maxDistance*2);
        if(t.opt.maxDistance > 60){
            t.opt.searchDistance = 60;
        }
        t.opt.searchShape = 'circle';
        t.mapDat = [];
        t.koordlist = [];
        t.firstX =  t.opt.startX - t.opt.maxDistance;
        t.lastX = t.opt.startX + t.opt.maxDistance;
        t.firstY =  t.opt.startY - t.opt.maxDistance;
        t.lastY = t.opt.startY + t.opt.maxDistance;
        t.tilesSearched = 0;
        t.tilesFound = 0;
        t.curX = t.firstX;
        t.curY = t.firstY;
        var xxx = t.MapAjax.normalize(t.curX);
        var yyy = t.MapAjax.normalize(t.curY);
        var element = 'pddatacity'+(t.lookup-1);
        ById(element).innerHTML = culang.searchSearched+' '+ xxx +','+ yyy;
        t.timerMap=setTimeout (function(){t.MapAjax.request (xxx, yyy, 60, t.mapCallback)}, 1000);
    },
    timerMap:null,
    mapCallback : function (left, top, width, rslt){
        var t = Tabs.DarkForest;
        if (!t.searchRunning)
            return;
        if (!rslt.ok){
            t.stopSearch (''+culang.mainError+': '+ rslt.errorMsg);
            return;
        }
        if (!Options.AttackRunning) {
            for (i=1;i<=Seed.cities.length;i++){
                AttackOptions.Update[i][1] = 0;
                GM_deleteValue('DF_' + Seed.player['name'] + '_city_' + i + '_' + getServerId())
            }
            var element = 'pddatacity'+(t.lookup-1);
            ById(element).innerHTML = ''+culang.dfCancelByUser+'';
            t.searchRunning = false;
            saveAttackOptions();
            return;
        }
        
        if (rslt.error_code == 9) {
            var element = 'pddatacity'+(t.lookup-1);
            document.getElementById(element).innerHTML = 'MAP-Error (60sec): '+ left +','+ top;
            setTimeout (function(){
                var element = 'pddatacity'+(t.lookup-1);
                document.getElementById(element).innerHTML = ''+culang.searchSearched+' '+ left +','+ top;
                t.MapAjax.request (left, top, 60, t.mapCallback);
            }, 61000);
            return;
        }
        map = rslt.data;

        for (k in map){
            if (map[k].tileType==54 || map[k].tileType==0) {
                var dist = distance (t.opt.startX, t.opt.startY, map[k].xCoord, map[k].yCoord);
                if(dist <= parseInt(AttackOptions.MaxDistance)) {
                    //Puffer fuer relevante Koords
                    //t.koordlist.push({x:map[k].xCoord,y:map[k].yCoord});
                    if (map[k].tileType==54 && AttackOptions.Levels[t.lookup][map[k].tileLevel]){
                        t.mapDat.push ({time:0,x:map[k].xCoord,y:map[k].yCoord,dist:dist,level:map[k].tileLevel});
                    }
                }
            }
        }

        t.tilesSearched += (t.opt.searchDistance*t.opt.searchDistance);

        t.curX += t.opt.searchDistance;
        if (t.curX > t.lastX){
            t.curX = t.firstX;
            t.curY += t.opt.searchDistance;
            if (t.curY > t.lastY){
                t.stopSearch(''+culang.dfFound+' ' + t.mapDat.length);
                //alert(t.koordlist.length);
                return;
            }
        }
        var x = t.MapAjax.normalize(t.curX);
        var y = t.MapAjax.normalize(t.curY);
        var element = 'pddatacity'+(t.lookup-1);
        ById(element).innerHTML = ' '+culang.searchSearched+' '+ x +','+ y;
        t.timerMap=setTimeout (function(){t.MapAjax.request (x, y, t.opt.searchDistance, t.mapCallback)}, MAP_DELAY);
    },


    stopSearch : function (msg){
        var t = Tabs.DarkForest;
        var element = 'pddatacity'+(t.lookup-1);
        ById(element).innerHTML = msg;
        GM_setValue('DF_' + Seed.player['name'] + '_city_' + t.lookup + '_' + getServerId(), JSON2.stringify(t.mapDat));
        AttackOptions.Update[t.lookup][0] = unixTime();
        AttackOptions.Update[t.lookup][1]++;
        t.searchRunning = false;
        saveAttackOptions();
        t.checkBarbData();
        return;
    },

    hide : function (){

    },

    show : function (){

    },

};
//</editor-fold>
//<editor-fold desc="SPLIT:Tabs/Raid.js">
/************************************************************************************
 *                        KOC POWER - TABS RAID                                        *
 ************************************************************************************/
Tabs.Raid = {
    tabDisabled : false,
    tabLabel: culang.mainRaid,
    tabOrder : TabOptions.toRaid,
    myDiv : null,
    rallypointlevel:null,
    knt:{},
    Troops:{},
    city:0,
    raidtimer:null,
    rslt:{},
    save:{},
    stopping:false,
    resuming:false,
    deleting:false,
    stopprogress:0,
    stopcount:0,
    activecount:0,
    count:0,
    timerLookup:null,
    timerPaint:null,
    timerReport:null,

    init : function (div){
        var t = Tabs.Raid;
        t.myDiv = div;
        t.raidtimer = setTimeout(t.checkRaids, 6000);
        var m = '<DIV class=pdxStat>'+culang.raidHead+'</div><TABLE width=100% height=0% class=pdxTab><TR align="center"><td colspan=2><INPUT id=pbraidtab type=submit value="'+culang.raidStopRaids+'" class="tab"><INPUT id=pbraidtabRes type=submit value="'+culang.raidResumeRaids+'" class="tab" ><INPUT id=pbraidtabDel type=submit value="'+culang.raidDeleteRaids+'" class="tab"></td><TR align="center">';
        m += '<TD><INPUT id=pbRaidStart type=submit value="'+culang.raidAutoReset+' = '+ (Options.RaidRunning?culang.buttonON:culang.buttonOFF) +'" ></td>';
        m += '<TD><INPUT id=pbsendraidreport type=checkbox '+ (Options.foodreport?'CHECKED':'') +'\> '+culang.raidReport+' ';
        m += '<INPUT id=pbsendreportint value='+ Options.MsgInterval +' type=text size=3 \> '+culang.raidReport2+'</td>';
        m += '</tr></table></div>';
        m += '<DIV class=pdxStat>'+culang.raidActiveHead+'</div><TABLE width=100% height=0% class=pdxTab><TR align="center">';
        m += '<TD><DIV style="margin-bottom:10px;"><span id=ptRaidCity></span></div></td></tr>';
        m+='<TR><TD><DIV style="margin-bottom:10px;"><span id=ptRaidTimer></span></div></td></tr></table>';
        m += '<DIV id=PaintRaids></div>';
        m += '<DIV class=pdxStat>'+culang.raidSavedHead+'</div><TABLE width=100% height=0% class=pdxTab><TR align="center">';
        m += '<DIV id=SavedRaids></div>';
        t.myDiv.innerHTML = m;
        if (Options.foodreport) {
            t.timerReport=setInterval(t.sendreport, 1*60*1000);
        }

        t.from = new CdispCityPicker ('ptRaidpicker', ById('ptRaidCity'), true, t.clickCitySelect, 0);
        ById('pbRaidStart').addEventListener('click', t.toggleRaidState, false);
        ById('pbsendraidreport').addEventListener('change', function(){
            Options.foodreport = ById('pbsendraidreport').checked;
            if (Options.foodreport) {
                clearInterval(t.timerReport);
                t.timerReport=setInterval(t.sendreport, 1*60*1000);
            } else {
                clearInterval(t.timerReport);
            }
            saveOptions();
        }, false);
        ById('pbsendreportint').addEventListener('change', function(){
            Options.MsgInterval = parseInt(ById('pbsendreportint').value);
            saveOptions();
        }, false);

        ById('pbraidtab').addEventListener('click', t.StopAllRaids, false);
        ById('pbraidtabRes').addEventListener('click', t.ResumeAllRaids, false);
        ById('pbraidtabDel').addEventListener('click', t.DeleteAllRaids, false);


        var serverID = getServerId();
        t.save = GM_getValue ('SavedRaids_'+serverID);
        if (t.save != undefined) t.save = JSON2.parse (t.save);


    },

    lookup : function (){
        var t = Tabs.Raid;
        t.activecount=0;
        t.stopcount=0;
        for (c=0; c< Seed.cities.length;c++) {
            cityID = 'city' + Seed.cities[c][0];
            for (b in Seed.queue_atkp[cityID]){
                destinationUnixTime = Seed.queue_atkp[cityID][b]['destinationUnixTime'];
                MarchStatus = Seed.queue_atkp[cityID][b]['marchStatus'];
                MarchType = Seed.queue_atkp[cityID][b]['marchType'];
                botMarchStatus = Seed.queue_atkp[cityID][b]['botMarchStatus'];
                if (MarchType == 9 &&  MarchStatus == 3 || MarchStatus==10) t.stopcount++;
                else if (MarchType == 9) t.activecount++;

            }
        }

        if (t.resuming == false && t.stopping == false && t.deleting == false && t.activecount != 0)
            if (ById('pbraidtab')) ById('pbraidtab').value = ''+culang.raidStopRaids+' ('+ t.activecount + ')'
            else if (t.resuming == false && t.stopping == false && t.deleting == false)
                if (ById('pbraidtab')) ById('pbraidtab').value = ''+culang.raidStopRaids+' ('+ t.activecount + ')'
        if (t.resuming == false && t.resuming == false && t.deleting == false && t.stopcount !=0)
            if (ById('pbraidtabRes')) ById('pbraidtabRes').value = ''+culang.raidResumeRaids+' ('+ t.stopcount + ')'
            else if (t.resuming == false && t.stopping == false && t.deleting == false)
                if (ById('pbraidtabRes')) ById('pbraidtabRes').value = ''+culang.raidResumeRaids+' ('+ t.stopcount + ')'
        if (t.resuming == false && t.stopping == false && t.deleting == false && t.stopcount !=0)
            if (ById('pbraidtabDel')) ById('pbraidtabDel').value = ''+culang.raidDeleteRaids+' ('+ t.stopcount + ')'
            else if (t.resuming == false && t.stopping == false && t.deleting == false)
                if (ById('pbraidtabDel')) ById('pbraidtabDel').value = ''+culang.raidDeleteRaids+' ('+ t.stopcount + ')'
    },

    paint : function ()    {
        var t = Tabs.Raid;

        var botMarchStat = {0:'Inactive',
            1:'Raiding',
            2:'Returning',
            3:'Stopped',
            4:'Resting',
            5:'Unknown',
            7:'Situation Changed',
            8:'Returning',
            9:'Aborting'};
        var botStat = {0:'Undefined',
            1:'Marching',
            2:'Returning',
            3:'Stopped',
            4:'Insufficient Troops',
            5:'Max Raids Exceeded',
            7:'Timed out',
            8:'Resting'};


        var o = '';
        if (t.rslt.settings != undefined) o+= '<B>'+culang.raidTimer+' <span class="boldRed">'+ timestr( 86400 - ( unixTime() - t.rslt.settings.lastUpdated )) +'</span></b>';
        ById('ptRaidTimer').innerHTML = o;

        var z ='<TABLE class=pdxTab><TR><TD width=60px align=center><A onclick="pbStopAll('+t.cityId+')">'+culang.raidStop+'</a></td><TD width=70px><u><b>'+culang.mainTime+'</b></u></td><TD width=85px><u><b>'+culang.shortCoordinate+'</b></u></td><TD width=50px><u><b>'+uW.g_js_strings.commonstr.level+'</b></u></td><TD width=50px></td><TD width=50px>&nbsp;</td></TR>';
        if (t.rslt['queue'] != ""){
            for (y in t.rslt['queue']) {
                if (t.rslt['queue'][y]['botMarches'] != undefined) {
                    for (k in Seed.queue_atkp['city' + t.cityId]){
                        if (Seed.queue_atkp['city' + t.cityId][k]['marchId'] == t.rslt['queue'][y]['botMarches']['marchId']) {
                            botMarchStatus = Seed.queue_atkp['city' + t.cityId][k]['botMarchStatus'];
                            MarchStatus = Seed.queue_atkp['city' + t.cityId][k]['marchStatus'];
                            restPeriod = (Seed.queue_atkp['city' + t.cityId][k]['restPeriod']/60);
                            destinationUnixTime = Seed.queue_atkp['city' + t.cityId][k]['destinationUnixTime'];
                            returnUnixTime = Seed.queue_atkp['city' + t.cityId][k]['returnUnixTime']
                            now = unixTime();
                            z+='<TR>';
                            if (MarchStatus == 1) z+='<TD align=center><img src="'+IMGmarchAttacking+'"></td>';
                            if (MarchStatus == 8 && (destinationUnixTime - now) <= 0 && botMarchStatus !=3 && returnUnixTime > now) z+='<TD align=center><img src="'+IMGmarchReturning+'"></td>';
                            if (MarchStatus == 3) z+='<TD align=center><img src="'+IMGmarchRaidStoppedDesat+'"></td>';
                            if (MarchStatus == 4 || (returnUnixTime < now  && botMarchStatus !=3)) z+='<TD align=center><img src="'+IMGmarchRaidReset+'"></td>';

                            if (destinationUnixTime >= now) z+='<TD>'+ timestr(Seed.queue_atkp['city' + t.cityId][k]['destinationUnixTime'] - unixTime())+'</td>';
                            if (destinationUnixTime <= now) {
                                if ((destinationUnixTime - now) <= 0 && returnUnixTime > now) z+='<TD>'+ timestr(returnUnixTime - now)+'</td>';
                                if (returnUnixTime <= now) z+='<TD>'+ timestr(now - returnUnixTime)+'</td>';
                            }
                        }
                    }
                    z+="<TD><a href='javascript:void(0)' onclick='cm.utils.CoordinateLinkController.onClick(event)' class='coordinateLink'>("+ t.rslt['queue'][y]['botMarches']['toXCoord'] +","+ t.rslt['queue'][y]['botMarches']['toYCoord']+")</a></td>";
                    z+='<TD align=center>'+ t.rslt['queue'][y]['botMarches']['toTileLevel'] +'</td>';
                    if (botMarchStatus == 3) z+='<TD><A onclick="pbEditRaid('+ y +')">'+culang.buttonEdit+'</a></td>';
                    else z+='<TD><FONT COLOR= "CCCCCC">'+culang.buttonEdit+'</font></td>';
                    if (botMarchStatus == 3) z+='<TD align=center><A onclick="pbDeleteRaid('+ t.rslt['queue'][y]['botMarches']['marchId']+')">'+culang.mainDelete+'</a></td>';
                    else z+='<TD align=center><FONT COLOR= "CCCCCC">'+culang.mainDelete+'</font></td>';
                    z +='<TD width=25px></td><TD>'+culang.raidRestPeriod+' '+ timestr(restPeriod) +'</td>';
                    z+='</tr>';
                }
            }
        }
        z+='</table>';
        if (t.rslt['queue'] == "") z ='<TABLE class=pdxTab ><TR><TD align=center><i><b>'+culang.raidNoFound+'</b></i></td></TR>';
        ById('PaintRaids').innerHTML = z;

        var check = true;
        if (t.save != ""){
            var a ='<TABLE class=pdxTab><TR><TD width=60px></td><TD width=70px></td><TD width=85px>'+culang.shortCoordinate+'</td><TD width=50px>'+uW.g_js_strings.commonstr.level+'</td><TD width=50px></td><TD width=50px></td></tr>';
            for (y in t.save){
                if (t.save[y] != undefined && t.cityId == t.save[y]['cityId']){
                    a +='<TR><TD align=center><A onclick="pbDeleteSavedRaid('+ t.save[y]['marchId'] +')"><img src="'+IMGdeleteButton+'" border=0 title="'+culang.raidDeleteNote+'"></a></td>';
                    a +="<TD></td><TD><FONT COLOR='#CC0000'><a href='javascript:void(0)' onclick='cm.utils.CoordinateLinkController.onClick(event)' class='coordinateLink'>("+t.save[y]['toXCoord']+","+t.save[y]['toYCoord']+")</a></font></td>";
                    a +='<TD align=center>'+t.save[y]['toTileLevel']+'</td>';
                    a +='<TD><A onclick="pbEditSavedRaid('+ y +')">'+culang.buttonEdit+'</a></td>';
                    a +='<TD align=center><A onclick="pbAddRaid('+ t.save[y]['marchId']+')">'+culang.buttonAdd+'</a></td></tr>';
                    check = false;
                }
            }
            m+='</table>';
        }

        if (check) a ='<TABLE class=pdxTab><TR><TD align=center><i>'+culang.raidSaveNoFound+'</i></td></TR>';

        ById('SavedRaids').innerHTML = a;

        unsafeWindow.pbDeleteRaid = t.DeleteRaid;
        unsafeWindow.pbEditRaid = t.EditRaid;
        unsafeWindow.pbAddRaid = t.AddRaid;
        unsafeWindow.pbDeleteSavedRaid = t.DeleteSavedRaid;
        unsafeWindow.pbEditSavedRaid = t.EditSavedRaid;
        unsafeWindow.pbStopAll = t.StopCityRaids;
    },

    DeleteSavedRaid : function (Id){
        var t = Tabs.Raid;
        for (yy=0;yy<t.save.length;yy++){
            if (t.save[yy]['marchId'] == Id){
                t.save.splice (yy,1);
            }
        }
        var serverID = getServerId();
        setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
        t.paint();
    },

    EditSavedRaid : function (y){
        var t = Tabs.Raid;
        var pop = new CPopup ('pbEditRaid', 0,0, 750,350, true);
        if (t.popFirst){
            pop.centerMe (mainPop.getMainDiv());
            t.popFirst = false;
        }
        pop.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.raidEditHead+'</div>';
        cityId =  t.save[y]['cityId'];

        var m = '<BR><TABLE id=pbRaidAdd height=0% class=pdxTab><TR align="center">';
        m+='<TR></tr><TR><TD width=25px>X= <INPUT id=toXCoord type=text size=3 maxlength=3 value='+t.save[y]['toXCoord']+'></td>';
        m+='<TD width=10px></td><TD widht=25px>Y= <INPUT id=toYCoord type=text size=3 maxlength=3 value='+ t.save[y]['toYCoord'] +'></td>';
        m+='<TD width=25px></td><TD>'+culang.mainRound+': '+ timestr((t.save[y]['returnUnixTime'] - t.save[y]['destinationUnixTime'])*2)+ '</td></tr></table>';

        m += '<BR><TABLE id=pbRaidAdd width=100% height=0% class=pdxTab><TR align="center">';
        m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSupplyTroop+'"></td>';
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt1']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleMilitiaman+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt2']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleScout+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt3']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddlePikeman+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt4']) +'</td></tr>'
        m += '<TR><TD><INPUT id=Unit1 type=text size=6 maxlength=6 value="'+ t.save[y]['unit1Count']+'"></td>';
        m += '<TD><INPUT id=Unit2 type=text size=6 maxlength=6 value="'+ t.save[y]['unit2Count']+'"></td>';
        m += '<TD><INPUT id=Unit3 type=text size=6 maxlength=6 value="'+ t.save[y]['unit3Count']+'"></td>';
        m += '<TD><INPUT id=Unit4 type=text size=6 maxlength=6 value="'+ t.save[y]['unit4Count']+'"></td></tr>';

        m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSwordsman+'"></td>';
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt5']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleArcher+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt6']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleCavalry+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt7']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleHeavyCavalry+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt8']) +'</td></tr>'
        m += '<TR><TD><INPUT id=Unit5 type=text size=6 maxlength=6 value="'+ t.save[y]['unit5Count']+'"></td>';
        m += '<TD><INPUT id=Unit6 type=text size=6 maxlength=6 value="'+ t.save[y]['unit6Count']+'"></td>';
        m += '<TD><INPUT id=Unit7 type=text size=6 maxlength=6 value="'+ t.save[y]['unit7Count']+'"></td>';
        m += '<TD><INPUT id=Unit8 type=text size=6 maxlength=6 value="'+ t.save[y]['unit8Count']+'"></td></tr>';

        m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSupplyWagon+'"></td>';
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt9']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleBallista+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt10']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleBatteringRam+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt11']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleCatapult+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt12']) +'</td></tr>'
        m += '<TR><TD><INPUT id=Unit9 type=text size=6 maxlength=6 value="'+ t.save[y]['unit9Count']+'"></td>';
        m += '<TD><INPUT id=Unit10 type=text size=6 maxlength=6 value="'+ t.save[y]['unit10Count']+'"></td>';
        m += '<TD><INPUT id=Unit11 type=text size=6 maxlength=6 value="'+ t.save[y]['unit11Count']+'"></td>';
        m += '<TD><INPUT id=Unit12 type=text size=6 maxlength=6 value="'+ t.save[y]['unit12Count']+'"></td></tr>';
        
        m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_13_30_s34.jpg"></td>';
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt13']) +'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_14_30_s34.jpg"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt14']) +'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_15_30_s34.jpg"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt15']) +'</td>'
        m += '<TD rowspan="2"></td>'
        m += '<TD></tr>'
        m += '<TR><TD><INPUT id=Unit13 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit13Count']+'"></td>';
        m += '<TD><INPUT id=Unit14 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit14Count']+'"></td>';
        m += '<TD><INPUT id=Unit15 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit15Count']+'"></td>';
        m += '<TD></td></tr>';
        
        m += '</table>';

        m += '<BR><CENTER><SELECT id=AddKnights type=list></select></center>';
        m+= '<BR><CENTER>'+ strButton20(''+culang.buttonSave+'', 'id=pbSaveRaid') +'</center>';

        pop.getMainDiv().innerHTML = m;

        t.getKnights(cityId);

        document.getElementById ('AddKnights').value =  t.save[y]['knightId'];
        document.getElementById ('pbSaveRaid').addEventListener ('click', function(){
            t.save[y]['knightId'] = parseInt(document.getElementById ('AddKnights').value);
            t.save[y]['toXCoord'] = parseInt(document.getElementById ('toXCoord').value);
            t.save[y]['toYCoord'] = parseInt(document.getElementById ('toYCoord').value);
            t.save[y]['unit1Count'] = parseInt(document.getElementById ('Unit1').value);
            t.save[y]['unit2Count'] = parseInt(document.getElementById ('Unit2').value);
            t.save[y]['unit3Count'] = parseInt(document.getElementById ('Unit3').value);
            t.save[y]['unit4Count'] = parseInt(document.getElementById ('Unit4').value);
            t.save[y]['unit5Count'] = parseInt(document.getElementById ('Unit5').value);
            t.save[y]['unit6Count'] = parseInt(document.getElementById ('Unit6').value);
            t.save[y]['unit7Count'] = parseInt(document.getElementById ('Unit7').value);
            t.save[y]['unit8Count'] = parseInt(document.getElementById ('Unit8').value);
            t.save[y]['unit9Count'] = parseInt(document.getElementById ('Unit9').value);
            t.save[y]['unit10Count'] = parseInt(document.getElementById ('Unit10').value);
            t.save[y]['unit11Count'] = parseInt(document.getElementById ('Unit11').value);
            t.save[y]['unit12Count'] = parseInt(document.getElementById ('Unit12').value);
            t.save[y]['unit13Count'] = parseInt(document.getElementById ('Unit13').value);
            t.save[y]['unit14Count'] = parseInt(document.getElementById ('Unit14').value);
            t.save[y]['unit15Count'] = parseInt(document.getElementById ('Unit15').value);
            var serverID = getServerId();
            setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
            pop.show (false);
        }, false);

        pop.show (true);
    },

    EditRaid : function (y){
        var t = Tabs.Raid;
        var pop = new CPopup ('pbEditRaid', 0,0, 750,350, true);
        if (t.popFirst){
            pop.centerMe (mainPop.getMainDiv());
            t.popFirst = false;
        }
        pop.getTopDiv().innerHTML = '<div class="popupBanner">'+culang.raidEditHead+'</div>';
        cityId = t.rslt['queue'][y]['botMarches']['cityId'];

        var m = '<BR><TABLE id=pbRaidAdd height=0% class=pdxTab><TR align="center">';
        m+='<TR></tr><TR><TD width=25px>X = <INPUT id=toXCoord type=text size=3 maxlength=3 value='+t.rslt['queue'][y]['botMarches']['toXCoord']+'></td>';
        m+='<TD width=10px></td><TD widht=25px>Y = <INPUT id=toYCoord type=text size=3 maxlength=3 value='+ t.rslt['queue'][y]['botMarches']['toYCoord'] +'></td>';
        m+='<TD width=25px></td><TD>'+culang.mainRound+': '+ timestr((t.rslt['queue'][y]['botMarches']['returnUnixTime'] - t.rslt['queue'][y]['botMarches']['destinationUnixTime'])*2)+ '</td></tr></table>';

        m += '<BR><TABLE id=pbRaidAdd width=100% height=0% class=pdxTab><TR align="center">';
        m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSupplyTroop+'"></td>';
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt1']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleMilitiaman+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt2']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleScout+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt3']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddlePikeman+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt4']) +'</td></tr>'
        m += '<TR><TD><INPUT id=Unit1 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit1Count']+'"></td>';
        m += '<TD><INPUT id=Unit2 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit2Count']+'"></td>';
        m += '<TD><INPUT id=Unit3 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit3Count']+'"></td>';
        m += '<TD><INPUT id=Unit4 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit4Count']+'"></td></tr>';

        m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSwordsman+'"></td>';
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt5']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleArcher+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt6']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleCavalry+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt7']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleHeavyCavalry+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt8']) +'</td></tr>'
        m += '<TR><TD><INPUT id=Unit5 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit5Count']+'"></td>';
        m += '<TD><INPUT id=Unit6 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit6Count']+'"></td>';
        m += '<TD><INPUT id=Unit7 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit7Count']+'"></td>';
        m += '<TD><INPUT id=Unit8 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit8Count']+'"></td></tr>';

        m += '<TR><TD rowspan="2"><img src="'+IMGmiddleSupplyWagon+'"></td>';
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt9']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleBallista+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt10']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleBatteringRam+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt11']) +'</td>'
        m += '<TD rowspan="2"><img src="'+IMGmiddleCatapult+'"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt12']) +'</td></tr>'
        m += '<TR><TD><INPUT id=Unit9 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit9Count']+'"></td>';
        m += '<TD><INPUT id=Unit10 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit10Count']+'"></td>';
        m += '<TD><INPUT id=Unit11 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit11Count']+'"></td>';
        m += '<TD><INPUT id=Unit12 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit12Count']+'"></td></tr>';
        
        m += '<TR><TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_13_30_s34.jpg"></td>';
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt13']) +'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_14_30_s34.jpg"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt14']) +'</td>'
        m += '<TD rowspan="2"><img src="http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_15_30_s34.jpg"></td>'
        m += '<TD>'+ addCommas(Seed.units['city'+cityId]['unt15']) +'</td>'
        m += '<TD rowspan="2"></td>'
        m += '<TD></tr>'
        m += '<TR><TD><INPUT id=Unit13 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit13Count']+'"></td>';
        m += '<TD><INPUT id=Unit14 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit14Count']+'"></td>';
        m += '<TD><INPUT id=Unit15 type=text size=6 maxlength=6 value="'+ t.rslt['queue'][y]['botMarches']['unit15Count']+'"></td>';
        m += '<TD></td></tr>';
        
        m += '</table>';

        m += '<BR><CENTER><SELECT id=AddKnights type=list></select></center>';
        m+= '<BR><CENTER>'+ strButton20('Save', 'id=pbRaidSave') +'</center>';

        pop.getMainDiv().innerHTML = m;

        t.getKnights(cityId);

        document.getElementById ('AddKnights').value =  t.rslt['queue'][y]['botMarches']['knightId'];
        document.getElementById ('pbRaidSave').addEventListener ('click', function(){
            var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

            params.pf = 0;
            params.ctrl = 'BotManager';
            params.action = 'editMarch';
            params.settings = {};
            params.settings.cityId = t.rslt['queue'][y]['botMarches']['fromCityId'];
            params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};
            params.queue[0].cityMarches.knightId = parseInt(document.getElementById ('AddKnights').value);
            params.queue[0].cityMarches.toXCoord =  parseInt(document.getElementById ('toXCoord').value);
            params.queue[0].cityMarches.toYCoord =  parseInt(document.getElementById ('toYCoord').value);
            params.queue[0].cityMarches.unit0Count = 0; //document.getElementById ('Unit0').value;
            params.queue[0].cityMarches.unit1Count =  parseInt(document.getElementById ('Unit1').value);
            params.queue[0].cityMarches.unit2Count = parseInt(document.getElementById ('Unit2').value);
            params.queue[0].cityMarches.unit3Count = parseInt(document.getElementById ('Unit3').value);
            params.queue[0].cityMarches.unit4Count = parseInt(document.getElementById ('Unit4').value);
            params.queue[0].cityMarches.unit5Count = parseInt(document.getElementById ('Unit5').value);
            params.queue[0].cityMarches.unit6Count = parseInt(document.getElementById ('Unit6').value);
            params.queue[0].cityMarches.unit7Count = parseInt(document.getElementById ('Unit7').value);
            params.queue[0].cityMarches.unit8Count = parseInt(document.getElementById ('Unit8').value);
            params.queue[0].cityMarches.unit9Count = parseInt(document.getElementById ('Unit9').value);
            params.queue[0].cityMarches.unit10Count = parseInt(document.getElementById ('Unit10').value);
            params.queue[0].cityMarches.unit11Count = parseInt(document.getElementById ('Unit11').value);
            params.queue[0].cityMarches.unit12Count = parseInt(document.getElementById ('Unit12').value);
            params.queue[0].cityMarches.unit13Count = parseInt(document.getElementById ('Unit13').value);
            params.queue[0].cityMarches.unit14Count = parseInt(document.getElementById ('Unit14').value);
            params.queue[0].cityMarches.unit15Count = parseInt(document.getElementById ('Unit15').value);
            params.queue[0].cityMarches.marchId =  t.rslt['queue'][y]['botMarches']['marchId'];

            new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
                method: "post",
                parameters: params,
                loading: true,
                onSuccess: function(transport){
                    var rslt = eval("(" + transport.responseText + ")");
                    if (rslt.ok) {
                        pop.show (false);
                        unsafeWindow.cityinfo_army();
                        setTimeout(unsafeWindow.update_seed_ajax, 250);
                        setTimeout(t.GetRaids, (750),Seed.cities[i][0]);
                    }
                },
            });
        }, false);

        pop.show (true);
    },

    DeleteRaid : function (Id){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        for (y in t.rslt['queue']) {
            if (t.rslt['queue'][y]['botMarches'] != undefined) {
                if (t.rslt['queue'][y]['botMarches']['marchId'] == Id) {
                    marchId = t.rslt['queue'][y]['botMarches']['marchId'];
                    cityId = t.rslt['queue'][y]['botMarches']['cityId'];
                    knightId = t.rslt['queue'][y]['botMarches']['knightId'];
                    toTileLevel = t.rslt['queue'][y]['botMarches']['toTileLevel'];
                    returnUnixTime = t.rslt['queue'][y]['botMarches']['returnUnixTime'];
                    destinationUnixTime = t.rslt['queue'][y]['botMarches']['destinationUnixTime'];
                    toXCoord = t.rslt['queue'][y]['botMarches']['toXCoord'];
                    toYCoord = t.rslt['queue'][y]['botMarches']['toYCoord'];
                    var units = {};
                    for (i=1;i<16;i++) units[i] = t.rslt['queue'][y]['botMarches']['unit'+i+'Count'];
                }
            }
        }

        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'deleteMarch';
        params.marchId = marchId;
        params.settings = {};
        params.settings.cityId = cityId;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    var serverID = getServerId();
                    t.save = GM_getValue ('SavedRaids_'+serverID);
                    if (t.save == undefined) t.save =new Array();
                    else t.save = JSON2.parse (t.save);

                    t.save.push ({
                        marchId:        marchId,
                        cityId:           cityId,
                        knightId:        knightId,
                        toTileLevel:    toTileLevel,
                        returnUnixTime:    destinationUnixTime,
                        returnUnixTime:    returnUnixTime,
                        toXCoord:        toXCoord,
                        toYCoord:        toYCoord,
                        unit1Count:     units[1],
                        unit2Count:     units[2],
                        unit3Count:     units[3],
                        unit4Count:     units[4],
                        unit5Count:     units[5],
                        unit6Count:     units[6],
                        unit7Count:     units[7],
                        unit8Count:     units[8],
                        unit9Count:     units[9],
                        unit10Count:     units[10],
                        unit11Count:     units[11],
                        unit12Count:     units[12],
                        unit13Count:     units[13],
                        unit14Count:     units[14],
                        unit15Count:     units[15],
                    });
                    var troops = Seed.units["city" + cityId];
                    for (var u = 1; u <= 15; ++u) {
                        var troop_number = parseInt(rslt["unit" + u + "Return"]);
                        if (isNaN(troop_number)) {
                            troop_number = parseInt(Seed.units["city" + cityId]["unt" + u]);
                        } else troop_number = parseInt(rslt["unit" + u + "Return"]) + parseInt(Seed.units["city" + cityId]["unt" + u]);
                        troops["unt" + u] = troop_number;
                    }
                    for (u in Seed.queue_atkp['city' + cityId]){
                        if (Seed.queue_atkp['city' + cityId][u]['marchId'] == marchId){
                            Seed.queue_atkp['city' + cityId][u] = "";
                            unsafeWindow.seed.queue_atkp['city' + cityId] = Seed.queue_atkp['city' + cityId];
                        }
                    }

                    for (u in Seed.knights['city' + cityId]){
                        if (Seed.knights['city' + cityId][u]['knightId'] == knightId){
                            Seed.knights['city' + cityId][u]["knightStatus"] = 1;
                            unsafeWindow.seed.knights['city' + cityId] = Seed.knights['city' + cityId];
                        }
                    }

                    GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));
                    t.save = null;
                    unsafeWindow.cityinfo_army();
                    setTimeout(unsafeWindow.update_seed_ajax, 250);
                    t.GetRaids(cityId);
                }
            },
        });
    },

    StopCityRaids : function (cityId){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'stopAll';
        params.settings = {};
        params.settings.cityId = cityId;

        new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {

                }
            },
        });
        setTimeout(t.GetRaids, (750), cityId);
    },

    StopAllRaids : function (){
        var t = Tabs.Raid;
        if (t.stopping == true || t.resuming == true || t.deleting == true) return;
        if (t.activecount == 0) return;
        t.stopping = true;
        for (i=0;i<Seed.cities.length;i++){
            setTimeout(t.DoAllStop, (i*1500),i);
        }
    },

    ResumeAllRaids : function (){
        var t = Tabs.Raid;
        if (t.stopping == true || t.resuming == true || t.deleting == true) return;
        if (t.stopcount == 0) return;
        t.resuming = true;
        for (i=0;i<Seed.cities.length;i++){
            setTimeout(t.DoAllResume, (i*1500),i);
        }
    },


    DeleteAllRaids : function (){
        var t = Tabs.Raid;
        if (t.stopping == true || t.resuming == true || t.deleting == true) return;
        if (t.stopcount == 0) return;
        t.deleting = true;
        count=0;
        t.count = t.stopcount;
        for (d=0; d< Seed.cities.length;d++) {
            cityID = 'city' + Seed.cities[d][0];
            for (e in Seed.queue_atkp[cityID]){
                destinationUnixTime = Seed.queue_atkp[cityID][e]['destinationUnixTime'];
                MarchStatus = Seed.queue_atkp[cityID][e]['marchStatus'];
                MarchType = Seed.queue_atkp[cityID][e]['marchType'];
                if (MarchType == 9 && (botMarchStatus == 3 || MarchStatus == 3)) {
                    count++;
                    setTimeout(t.DoAllDelete, (count*1250), (Seed.queue_atkp[cityID][e]['marchId']),d,count);
                }
            }
        }
    },


    DoAllStop: function(i) {
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'stopAll';
        params.settings = {};
        params.settings.cityId = Seed.cities[i][0];

        new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    t.stopprogress = t.stopprogress + (100/Seed.cities.length);

                    if (ById("pbraidtab")) ById("pbraidtab").value=''+culang.raidStopping+': '+ t.stopprogress.toFixed(0) + '%';
                    if (t.stopprogress.toFixed(0) == 100) {
                        t.stopprogress = 0;
                        setTimeout(
                            function(){
                                if (ById("pbraidtab")) ById("pbraidtab").value=''+culang.raidStopRaids+' ('+ t.activecount + ')';
                                t.stopping = false;

                            }, (5000));

                    }
                }
                else {
                    if (rslt.msg == "The system is busy, please try again later") setTimeout (t.DoAllStop, (2000),i);
                    else {
                        t.stopprogress = t.stopprogress + (100/Seed.cities.length);
                        if (ById("pbraidtab")) ById("pbraidtab").value=''+culang.raidStopping+': '+ t.stopprogress.toFixed(0) + '%';

                        if (t.stopprogress.toFixed(0) == 100) {
                            t.stopprogress = 0;
                            setTimeout(function(){
                                if (ById("pbraidtab")) ById("pbraidtab").value=''+culang.raidStopRaids+' ('+ t.activecount + ')';
                                t.stopping = false;
                            }, (5000));

                        }
                    }
                }
            },
        });
    },

    DoAllResume: function(i) {
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'resumeAll';
        params.settings = {};
        params.settings.cityId = Seed.cities[i][0];

        new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    t.stopprogress = t.stopprogress + (100/Seed.cities.length);
                    if (ById("pbraidtabRes")) ById("pbraidtabRes").value=''+culang.raidResuming+': '+ t.stopprogress.toFixed(0) + '%';
                    if (t.stopprogress.toFixed(0) == 100) {
                        t.stopprogress = 0;
                        setTimeout(function(){

                            if (ById("pbraidtabRes")) ById("pbraidtabRes").value=''+culang.raidResumeRaids+' ('+ t.stopcount + ')';

                            t.resuming = false;
                        }, (5000));
                    }
                } else {
                    if (rslt.msg == "The system is busy, please try again later") setTimeout (t.DoAllResume, (2000),i);
                    else {
                        t.stopprogress = t.stopprogress + (100/Seed.cities.length);
                        if (ById("pbraidtabRes")) ById("pbraidtabRes").value=''+culang.raidResuming+': '+ t.stopprogress.toFixed(0) + '%';
                        if (t.stopprogress.toFixed(0) == 100) {
                            t.stopprogress = 0;
                            setTimeout(function(){
                                if (ById("pbraidtabRes")) ById("pbraidtabRes").value=''+culang.raidResumeRaids+' ('+ t.stopcount + ')';
                                t.resuming = false;}, (5000));
                        }
                    }
                }
            },
        });
    },

    DoAllDelete : function (Id,city,count){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        cityID = 'city'+ Seed.cities[city][0];
        for (f in Seed.queue_atkp[cityID]){
            if (Seed.queue_atkp[cityID][f]['marchId'] == Id) {
                marchId = Seed.queue_atkp[cityID][f]['marchId'];
                cityId = Seed.queue_atkp[cityID][f]['cityId'];
                knightId = Seed.queue_atkp[cityID][f]['knightId'];
                toTileLevel = Seed.queue_atkp[cityID][f]['toTileLevel'];
                returnUnixTime = Seed.queue_atkp[cityID][f]['returnUnixTime'];
                destinationUnixTime = Seed.queue_atkp[cityID][f]['destinationUnixTime'];
                toXCoord = Seed.queue_atkp[cityID][f]['toXCoord'];
                toYCoord = Seed.queue_atkp[cityID][f]['toYCoord'];
                var units = {};
                for (i=1;i<16;i++) units[i] = Seed.queue_atkp[cityID][f]['unit'+i+'Count'];
            }
        }

        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'deleteMarch';
        params.marchId = marchId;
        params.settings = {};
        params.settings.cityId = cityId;

        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt != "") {
                    var serverID = getServerId();
                    t.save = GM_getValue ('SavedRaids_'+serverID, "[]");
                    if (t.save != undefined) t.save = JSON2.parse (t.save);
                    if (t.save == undefined) t.save =new Array();

                    t.save.push ({
                        marchId:        marchId,
                        cityId:           cityId,
                        knightId:        knightId,
                        toTileLevel:    toTileLevel,
                        returnUnixTime:    destinationUnixTime,
                        returnUnixTime:    returnUnixTime,
                        toXCoord:        toXCoord,
                        toYCoord:        toYCoord,
                        unit1Count:     units[1],
                        unit2Count:     units[2],
                        unit3Count:     units[3],
                        unit4Count:     units[4],
                        unit5Count:     units[5],
                        unit6Count:     units[6],
                        unit7Count:     units[7],
                        unit8Count:     units[8],
                        unit9Count:     units[9],
                        unit10Count:     units[10],
                        unit11Count:     units[11],
                        unit12Count:     units[12],
                        unit13Count:     units[13],
                        unit14Count:     units[14],
                        unit15Count:     units[15],
                    });

                    var troops = Seed.units["city" + cityId];
                    for (var u = 1; u <= 15; ++u) {
                        var troop_number = parseInt(rslt["unit" + u + "Return"]);
                        if (isNaN(troop_number)) {
                            troop_number = parseInt(Seed.units["city" + cityId]["unt" + u]);
                        } else troop_number = parseInt(rslt["unit" + u + "Return"]) + parseInt(Seed.units["city" + cityId]["unt" + u]);
                        troops["unt" + u] = troop_number;
                    }

                    setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
                    unsafeWindow.cityinfo_army();
                    setTimeout(unsafeWindow.update_seed_ajax, 250);
                }
            },
        });
        t.stopprogress = count * (100/t.count);
        if (ById("pbraidtabRes")) ById("pbraidtabDel").value=''+culang.raidDeleting+' '+ t.stopprogress.toFixed(0) + '%';
        if (t.stopprogress.toFixed(0) == 100) {
            t.stopprogress = 0;
            t.GetRaids(cityId);
        }

    },
    AddRaid : function (Id){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        update = {};

        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'saveMarch';
        params.settings = {};
        params.queue = {0:{botMarches:{botMarchStatus:1,botState:1},cityMarches:{}}};

        for (y in t.save){
            if (t.save[y]['marchId'] == Id){
                params.settings.cityId = t.save[y]['cityId'];
                params.queue[0].cityMarches.knightId = t.save[y]['knightId'];
                params.queue[0].cityMarches.toXCoord = t.save[y]['toXCoord'];
                params.queue[0].cityMarches.toYCoord = t.save[y]['toYCoord'];
                params.queue[0].cityMarches.unit0Count = 0;
                params.queue[0].cityMarches.unit1Count = t.save[y]['unit1Count'];
                params.queue[0].cityMarches.unit2Count = t.save[y]['unit2Count'];
                params.queue[0].cityMarches.unit3Count = t.save[y]['unit3Count'];
                params.queue[0].cityMarches.unit4Count = t.save[y]['unit4Count'];
                params.queue[0].cityMarches.unit5Count = t.save[y]['unit5Count'];
                params.queue[0].cityMarches.unit6Count = t.save[y]['unit6Count'];
                params.queue[0].cityMarches.unit7Count = t.save[y]['unit7Count'];
                params.queue[0].cityMarches.unit8Count = t.save[y]['unit8Count'];
                params.queue[0].cityMarches.unit9Count = t.save[y]['unit9Count'];
                params.queue[0].cityMarches.unit10Count = t.save[y]['unit10Count'];
                params.queue[0].cityMarches.unit11Count = t.save[y]['unit12Count'];
                params.queue[0].cityMarches.unit12Count = t.save[y]['unit12Count'];
                params.queue[0].cityMarches.unit13Count = t.save[y]['unit13Count'];
                params.queue[0].cityMarches.unit14Count = t.save[y]['unit14Count'];
                params.queue[0].cityMarches.unit15Count = t.save[y]['unit15Count'];
            }
        }

        new AjaxRequest2(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    t.GetRaids(params.settings.cityId);
                    unsafeWindow.cityinfo_army();
                    setTimeout(unsafeWindow.update_seed_ajax, 250);
                    for (yy=0;yy<t.save.length;yy++){
                        if (t.save[yy]['marchId'] == Id){
                            t.save.splice (yy,1);
                        }
                    }
                    var serverID = getServerId();
                    setTimeout (function (){GM_setValue ('SavedRaids_'+serverID, JSON2.stringify(t.save));}, 0);
                    t.paint();
                } else {
                    alert('Error: '+ rslt.msg);
                }
            },
        });
    },


    getKnights : function(cityId){
        var t = Tabs.Raid;
        var knt = new Array();
        var status ="";
        for (k in Seed.knights['city' + cityId]){
            if ( Seed.leaders['city' + cityId]["resourcefulnessKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["politicsKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["combatKnightId"] != Seed.knights['city' + cityId][k]["knightId"] && Seed.leaders['city' + cityId]["intelligenceKnightId"] != Seed.knights['city' + cityId][k]["knightId"]){
                if (Seed.knights['city' + cityId][k]["knightStatus"] == 1 ) status = "Free";
                else status = "Marching";
                knt.push ({
                    Name:   Seed.knights['city' + cityId][k]["knightName"],
                    Combat:    parseInt(Seed.knights['city' + cityId][k]["combat"]),
                    ID:        Seed.knights['city' + cityId][k]["knightId"],
                    Status: status,
                });
            }
        }
        knt = knt.sort(function sort(a,b) {a = a['Combat'];b = b['Combat'];return a == b ? 0 : (a > b ? -1 : 1);});
        ById('AddKnights').options.length=0;
        var o = document.createElement("option");
        o.text = '-- '+culang.mainSelect+' --';
        o.value = 0;
        ById("AddKnights").options.add(o);
        for (k in knt){
            if (knt[k]["Name"] !=undefined){
                var o = document.createElement("option");
                o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +') (' + knt[k]["Status"] +')');
                o.value = knt[k]["ID"];
                ById("AddKnights").options.add(o);
            }
        }
    },


    clickCitySelect : function (city){
        var t = Tabs.Raid;
        t.cityId = city['id'];
        t.GetRaids(t.cityId);
    },

    checkRaids : function (){
        var t = Tabs.Raid;
        var now = unixTime();
        if(!Options.RaidRunning) return;
        if ( (now - Options.RaidReset) > 7200 ) {
            Options.RaidReset = now;
            saveOptions();
            for (g=0;g<Seed.cities.length;g++){
                t.citiesdone = "";
                setTimeout(t.resetRaids, (1500*g), Seed.cities[g][0],Seed.cities[g][1]);
            }
        }
        t.raidtimer = setTimeout(t.checkRaids, 60*60*1000); // toute les heures !
    },

    GetRaids : function(cityId){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'getMarches';
        params.settings = {};
        params.settings.cityId = cityId;


        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");

                if (rslt.ok) {
                    t.rslt = rslt;
                    t.paint();
                    unsafeWindow.cityinfo_army();
                    setTimeout(unsafeWindow.update_seed_ajax, 250);
                }
            },
        });
    },

    resetRaids : function(cityId,cityName){
        var t = Tabs.Raid;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);

        params.pf = 0;
        params.ctrl = 'BotManager';
        params.action = 'resetRaidTimer';
        params.settings = {};
        params.settings.cityId = cityId;


        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/_dispatch.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            loading: true,
            onSuccess: function(transport){
                var rslt = eval("(" + transport.responseText + ")");
                if (rslt.ok) {
                    actionLog(""+culang.mainRaid+""," "+culang.logResetTimer+" <span class=boldGreen>"+cityName+"</span> "+culang.logResetTimer2+"");
                    unsafeWindow.cityinfo_army();
                    setTimeout(unsafeWindow.update_seed_ajax, 250);
                    t.citiesdone += cityName + ' ';
                }
            },
        });
    },
    sendreport: function(){
        var t = Tabs.Raid;
        if(!Options.foodreport) return;
        var now = new Date().getTime()/1000.0;
        now = now.toFixed(0);
        if (now < (parseInt(Options.LastReport)+(Options.MsgInterval*60*60))) return;

        var total = 0;
        var message = ''+culang.raidReportStats+' %0A';
        message += '%0A '+culang.raidReportFoodGain+' '+ Options.MsgInterval +' '+culang.raidReportFoodGain2+' %0A';
        for (q=1;q<=Seed.cities.length;q++){
            var cityID = 'city' + Seed.cities[q-1][0];
            var gain = parseInt(Seed.resources[cityID]['rec1'][0] / 3600) - Options.Foodstatus[q];
            message+= ''+culang.mainCastle+': '+Seed.cities[q-1][1] + ' '+culang.raidReportFoodGainStat+' ' + addCommas(Options.Foodstatus[q]) + ' '+culang.raidReportFoodGainStat2+' ' + addCommas(parseInt(Seed.resources[cityID]['rec1'][0] / 3600)) + ' '+culang.raidReportFoodGainStat3+' ';
            message += addCommas(gain)  + '%0A';
            total += gain;
            Options.Foodstatus[q] = parseInt(Seed.resources[cityID]['rec1'][0] / 3600);
        }
        message += '%0A '+culang.raidReportFoodGainTotal+' '+addCommas(total)+'%0A';

        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.emailTo = Seed.player['name'];
        params.subject = ""+culang.raidReportOverview+"";
        params.message = message;
        params.requestType = "COMPOSED_MAIL";
        new AjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getEmail.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (message) {
                var rslt = eval("(" + message.responseText + ")");
                if (rslt.ok) {
                } else {
                }
            },
            onFailure: function () {
            },
        });

        Options.LastReport = now;
        saveOptions();
    },

    toggleRaidState : function (){
        var t = Tabs.Raid;
        if(Options.RaidRunning){
            Options.RaidRunning = false;
            t.raidtimer = null;
            ById('pbRaidStart').value = culang.raidAutoReset+' = '+culang.buttonOFF;
        } else {
            Options.RaidRunning = true;
            t.raidtimer = setTimeout(t.checkRaids, 5000);
            ById('pbRaidStart').value = culang.raidAutoReset+' = '+culang.buttonON;
        }
        saveOptions();
    },


    hide : function (){
        var t = Tabs.Raid;
        clearInterval(t.timerPaint);
        clearInterval(t.timerLookup);
    },

    show : function (){
        var t = Tabs.Raid;
        clearInterval(t.timerPaint);
        clearInterval(t.timerLookup);
        t.timerPaint = setInterval (t.paint,2000);
        t.timerLookup = setInterval(t.lookup, 3500);
    },
};
//</editor-fold>


unsafeWindow.ptGotoMap = function (x, y){
    setTimeout (function (){
        ById('mapXCoor').value = x;
        ById('mapYCoor').value = y;
        unsafeWindow.reCenterMapWithCoor();
        var a = ById("mod_views").getElementsByTagName("a");
        for (var b = 0; b < a.length; b++) {
            a[b].className = ""
        }
        ById('mod_views_map').className = "sel";
        ById("maparea_city").style.display = 'none';
        ById("maparea_fields").style.display = 'none';
        ById("maparea_map").style.display = 'block';
        unsafeWindow.tutorialClear()
    }, 0);
};

function clickWinKs(win,obj,evtName) {
    var evt = win.document.createEvent("MouseEvents");
    evt.initMouseEvent(evtName, true, true, win, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    return !obj.dispatchEvent(evt);
}
function searchDOM (node, condition, maxLevel, doMult){
    var found = [];
    eval ('var compFunc = function (node) { return ('+ condition +') }');
    doOne(node, 1);
    if(!doMult){
        if (found.length==0)
            return null;
        return found[0];
    }
    return found;
    function doOne (node, curLevel){
        try {
            if (compFunc(node))
                found.push(node);
        } catch (e){
        }
        if (!doMult && found.length>0)
            return;
        if (++curLevel<maxLevel && node.childNodes!=undefined)
            for (var c=0; c<node.childNodes.length; c++)
                doOne (node.childNodes[c], curLevel);
    }
}

function CwaitForElement (id, timeout, notify){
    this.check = check;
    this.end = new Date().getTime() + timeout;
    var t = this;
    this.check();
    function check(){
        if (document.getElementById (id))
            notify (true);
        else if (new Date().getTime() > t.end)
            notify (false);
        else
            setTimeout (t.check, 250);
    }
}
function CdialogCancelContinue (msg, canNotify, contNotify, centerElement){
    var pop = new CPopup ('ptcancont', 10, 10, 400,200, true, canNotify);
    if (centerElement)
        pop.centerMe(centerElement);
    else
        pop.centerMe(document.body);
    pop.getMainDiv().innerHTML = '<TABLE class=pdxTab align=center style="height: 100%"><TR align=center height=90%><TD>'+ msg +'</td></tr>\
      <TR align=center><TD><INPUT id=ptok type=submit value="'+culang.mainOK+'" \> &nbsp; &nbsp; </td></tr></table>';
    pop.getTopDiv().innerHTML = '<div class="popupBanner">'+ScriptName+'</div>';
    document.getElementById('ptok').addEventListener ('click', function (){pop.destroy(false); if (canNotify) canNotify();}, false);
    pop.show(true);
}

function saveAttackOptions (){
    var serverID = getServerId();
    setTimeout (function (){GM_setValue ('AttackOptions_'+serverID, JSON2.stringify(AttackOptions));}, 0);
}

function readAttackOptions (){
    var serverID = getServerId();
    s = GM_getValue ('AttackOptions_'+serverID);
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    AttackOptions[k][kk] = opts[k][kk];
            else
                AttackOptions[k] = opts[k];
        }
    }
}
function saveKsRange (){
  var serverID = getServerId();
  setTimeout (function (){GM_setValue ('KsRange_'+serverID, JSON2.stringify(KsRange));}, 0);
}

function readKsRange (){
  var serverID = getServerId();
  s = GM_getValue ('RCOptions_'+serverID);
  if (s != null){
    opts = JSON2.parse (s);
    for (k in opts){
      if (matTypeof(opts[k]) == 'object')
        for (kk in opts[k])
          KsRange[k][kk] = opts[k][kk];
      else
        KsRange[k] = opts[k];
    }
  }
}

 /*******************   KOC Map interface ****************/
// 0:bog, 10:grassland, 11:lake, 20:woods, 30:hills, 40:mountain, 50:plain, 51:city / barb, 53:misted city
function CMapAjax (){
    this.normalize = normalize;
    this.request = request;

    function request (left, top, width, notify){
        var left = parseInt(left / 5) * 5;
        var top = parseInt(top / 5) * 5;
        var width = parseInt((width+4) / 5) * 5;

        var blockString = generateBlockList(left, top, width);
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.blocks = blockString;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fetchMapTiles.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                notify(left, top, width, rslt);
            },
            onFailure: function (rslt) {
                notify(left, top, width, rslt);
            }
        });
        function generateBlockList (left, top, width) {
            var width5 = parseInt(width / 5);
            var bl = [];
            for (x=0; x<width5; x++){
                var xx = left + (x*5);
                if (xx > 745)
                    xx -= 750;
                for (y=0; y<width5; y++){
                    var yy = top + (y*5);
                    if (yy > 745)
                        yy -= 750;
                    bl.push ('bl_'+ xx +'_bt_'+ yy);
                }
            }
            return bl.join(",");
        }
    }

    function normalize  (x){
        if ( x >= 750)
            x -= 750;
        else if (x < 0)
            x += 750;
        return parseInt (x/5) * 5;
    }
}

function distance (d, f, c, e) {
    var a = 750;
    var g = a / 2;
    var b = Math.abs(c - d);
    if (b > g)
        b = a - b;
    var h = Math.abs(e - f);
    if (h > g)
        h = a - h;
    return Math.round(100 * Math.sqrt(b * b + h * h)) / 100;
};
function setTabStyle (e, selected){
    if (selected){
        if (Options.pdxMenuLeft) {  e.className = 'ksTabSelLeft'; } else { e.className = 'ksTabSel'; }
    } else {
        if (Options.pdxMenuLeft) {  e.className = 'ksTabNotSelLeft'; } else { e.className = 'ksTabNotSel'; }
    }
}


function clickedTab2 (e){
    who2 = e.target.id.substring(3);
    newObj2 = Tabs2[who2];
    if (Tabs2[currentName2]==undefined) {
        currentName2 = 'Movement';
    }
    currentObj2 = Tabs2[currentName2];
    if (currentName2 != who2){
        setTabStyle (document.getElementById ('ab'+currentName2), false);
        setTabStyle (document.getElementById ('ab'+who2), true);
        if (currentObj2){
            currentObj2.hide ();
            currentObj2.getContent().style.display = 'none';
        }
        currentName2 = who2;
        Options.currentTab2 = currentName2;
        cont = newObj2.getContent();
        newObj2.getContent().style.display = 'block';
    }
    newObj2.show();
}

function mouseMainTab (me){   // right-click on main button resets window location
    if (me.button == 2){
        var c = getClientCoords (ById('main_engagement_tabs'));
        mainPop.setLocation ({x: c.x+4, y: c.y+c.height});
    }
}

function eventHideShow (){
    if (mainPop.toggleHide(mainPop)){
        tabManager.showTab();
        Options.pbWinIsOpen = true;
    } else {
        tabManager.hideTab();
        Options.pbWinIsOpen = false;
    }
    saveOptions();
}

function hideMe (){
    mainPop.show (false);
    tabManager.hideTab();
    Options.pbWinIsOpen = false;
    saveOptions();
}

function showMe (){
    mainPop.show (true);
    tabManager.showTab();
    Options.pbWinIsOpen = true;
    saveOptions();
}


function mouseMainTab2 (me){
    if (me.button == 2){
        var c = getClientCoords (ById('main_engagement_tabs'));
        mainPop2.setLocation ({x: c.x+4, y: c.y+c.height});
    }
}

function eventHideShow2 (){
    if (mainPop2.toggleHide(mainPop2)){
        if (Tabs2[currentName2]==undefined) {
            currentName2 = 'Movement';
        }
        Tabs2[currentName2].show();
        Options.ptWin2IsOpen = true;
    } else {
        if (Tabs2[currentName2]==undefined) {
            currentName2 = 'Movement';
        }
        Tabs2[currentName2].hide();
        Options.ptWin2IsOpen = false;
    }
    saveOptions();
}

function reloadKOC (){
    var serverId = getServerId();
    if(serverId == '??') window.location.reload(true);
    var goto = window.location.protocol+'//apps.facebook.com/kingdomsofcamelot/?s='+serverId;
    if(document.URL.match(/standalone=1/i)){
        goto = window.location.protocol+'//www.kabam.com/kingdoms-of-camelot/play?s='+serverId;
    }
    var t = '<FORM target="_top" action="'+ goto +'" method=post><INPUT id=xxpbButReload type=submit value=RELOAD><INPUT type=hidden name=s value="'+ serverId +'"</form>';
    var e = document.createElement ('div');
    e.innerHTML = t;
    document.body.appendChild (e);
    setTimeout (function (){document.getElementById('xxpbButReload').click();}, 0);
}

function getResearchLevels () {
    for (var t=1; t < 18; t++) {
        if (t != 7) {
            researchLevels[t] = {};
            researchLevels[t].Id = t;
            researchLevels[t].Name = unsafeWindow.techcost['tch'+t][0].replace (/&#39;/img, '\'');
            researchLevels[t].Level = parseInt(Seed.tech['tch'+t]);
            researchLevels[t].NextLevelETA = 0;
            researchLevels[t].Image = 'https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/tech/'+t+'_s33.png';
        }
    }
    var q;
    var now = unixTime();
    for(var i=0; i<Cities.numCities; i++) { // each city
        var cityID = 'city'+ Cities.cities[i].id;
        q = Seed.queue_tch[cityID];
        if (q[0] != undefined)
            researchLevels[parseInt(q[0][0])].NextLevelETA = parseInt(q[0][3]) - now;
    }
}
function getResearchLevels2 () {
    for (var t=1; t < 7; t++) {
        researchLevels2[t] = {};
        researchLevels2[t].Id = t;
        researchLevels2[t].Name = unsafeWindow.techcost2['tch'+t][0].replace (/&#39;/img, '\'');
        researchLevels2[t].Level = parseInt(Seed.tech2['tch'+t]);
        researchLevels2[t].NextLevelETA = 0;
        researchLevels2[t].Image = 'https://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/tech2/'+t+'_s33.png';
    }
    var q;
    var now = unixTime();
    for(var i=0; i<Cities.numCities; i++) { // each city
        var cityID = 'city'+ Cities.cities[i].id;
        q = Seed.queue_tch2[cityID];
        if (q[0] != undefined)
            researchLevels2[parseInt(q[0][0])].NextLevelETA = parseInt(q[0][3]) - now;
    }
}
function getTroopDefTrainEstimates(cityID){
    var city = {};
    var b = Seed.buildings['city' + cityID];
    city.numBarracks = 0;
    city.maxBarracks = 0;
    city.numDruidBarracks = 0;
    city.maxDruidBarracks = 0;
    city.numFeyBarracks = 0;
    city.maxFeyBarracks = 0;
    city.numBritonBarracks = 0;
    city.maxBritonBarracks = 0;
    city.totLevelsBarracks = 0;
    city.totLevelsAscBarracks = 0;
    city.blacksmithLevel = 0;
    city.stableLevel = 0;
    city.workshopLevel = 0;
    city.wallLevel = 0;
    for (var g in b) {
        var building = b[g];
        var btype = parseIntNan(building[0]);
        var blvl = parseIntNan(building[1]);
        if (btype == 13) {                            //Kaserne
            city.numBarracks++;
            city.totLevelsBarracks += parseInt(blvl);
            if (blvl > city.maxBarracks) city.maxBarracks = blvl;
        }
        if (btype == 22) {                            //Asc Kaserne
            city.numDruidBarracks++;
            city.totLevelsDruidBarracks += parseInt(blvl);
            if (blvl>city.maxDruidBarracks) city.maxDruidBarracks = blvl;
        }
        if (btype == 24) {                            //Asc Kaserne
            city.numFeyBarracks++;
            city.totLevelsFeyBarracks += parseInt(blvl);
            if (blvl>city.maxFeyBarracks) city.maxFeyBarracks = blvl;
        }
        if (btype == 26) {                            //Asc Kaserne
            city.numBritonBarracks++;
            city.totLevelsBritonBarracks += parseInt(blvl);
            if (blvl>city.maxBritonBarracks) city.maxBritonBarracks = blvl;
        }
        if (btype == 15) city.blacksmithLevel = blvl;    //Schmied
        if (btype == 16) city.workshopLevel = blvl;   //Werkstatt
        if (btype == 17) city.stableLevel = blvl;     //Stallung
        if (btype == 19) city.wallLevel = blvl;       //Mauer
    }

    //Forschungslevel
    city.loggingLevel = parseInt(Seed.tech["tch2"]);
    city.geometryLevel = parseInt(Seed.tech["tch5"]);
    city.eagleEyesLevel = parseInt(Seed.tech["tch6"]);
    city.poisonedEdgeLevel = parseInt(Seed.tech["tch8"]);
    city.metalAlloysLevel = parseInt(Seed.tech["tch9"]);
    city.featherweightPowderLevel = parseInt(Seed.tech["tch10"]);
    city.alloyHorseshoesLevel = parseInt(Seed.tech["tch12"]);
    city.fletchingLevel = parseInt(Seed.tech["tch13"]);
    city.giantsStrengthLevel = parseInt(Seed.tech["tch16"]);
    
    //Ritter
    var now = unixTime();
    city.marshallCombatScore = 0;
    city.foremanBasePoliticsScore = 0;
    city.foremanCombatScore = 0;    
    var s = Seed.knights['city'+cityID];
    if (s) {
        s = s["knt" + Seed.leaders['city'+cityID].combatKnightId];
        if (s){
            city.marshallCombatScore = s.combat;
            if (s.combatBoostExpireUnixtime > now)
                city.marshallCombatScore *= 1.25;
        }
    }
    var s = Seed.knights['city'+cityID];
    if (s) {
        s = s["knt" + Seed.leaders['city'+cityID].politicsKnightId];
        if (s) {
            city.foremanBasePoliticsScore = s.politics;
            city.foremanCombatScore = s.combat;
            if (s.politicsBoostExpireUnixtime > now)
                city.foremanBasePoliticsScore *= 1.25;
                city.foremanCombatScore *= 1.25;
        }
    }
    
    //Berechnen der Ausbildungszeiten fuer Truppen
    for (var b = 1; b < 16; b++) {
        city['Troop'+b+'Time'] = TroopTrainTime(b, 10000, cityID);
        if (b == 1 && !(city.maxBarracks > 0)) city['Troop'+b+'Time'] = 0;
        if (b == 2 && !(city.maxBarracks > 0)) city['Troop'+b+'Time'] = 0;
        if (b == 3 && !(city.maxBarracks > 1 && city.eagleEyesLevel > 0)) city['Troop'+b+'Time'] = 0;
        if (b == 4 && !(city.maxBarracks > 1 && city.poisonedEdgeLevel > 0)) city['Troop'+b+'Time'] = 0;
        if (b == 5 && !(city.maxBarracks > 2 && city.workshopLevel > 0 && city.metalAlloysLevel > 0)) city['Troop'+b+'Time'] = 0;
        if (b == 6 && !(city.maxBarracks > 3 && city.fletchingLevel > 0)) city['Troop'+b+'Time'] = 0;
        if (b == 7 && !(city.maxBarracks > 4 && city.stableLevel > 0 && city.alloyHorseshoesLevel > 0)) city['Troop'+b+'Time'] = 0;
        if (b == 8 && !(city.maxBarracks > 6 && city.workshopLevel > 4 && city.stableLevel > 4 && city.alloyHorseshoesLevel > 4)) city['Troop'+b+'Time'] = 0;
        if (b == 9 && !(city.maxBarracks > 5 && city.stableLevel > 0 && city.blacksmithLevel > 2 && city.featherweightPowderLevel > 0)) city['Troop'+b+'Time'] = 0;
        if (b == 10 && !(city.maxBarracks > 7 && city.stableLevel > 1 && city.blacksmithLevel > 4 && city.geometryLevel > 4 && city.fletchingLevel > 5)) city['Troop'+b+'Time'] = 0;
        if (b == 11 && !(city.maxBarracks > 8 && city.workshopLevel > 4 && city.stableLevel > 2 && city.blacksmithLevel > 6 && city.metalAlloysLevel > 7 && city.geometryLevel > 6)) city['Troop'+b+'Time'] = 0;
        if (b == 12 && !(city.maxBarracks > 9 && city.stableLevel > 1 && city.blacksmithLevel > 8 && city.geometryLevel > 9 && city.fletchingLevel > 9)) city['Troop'+b+'Time'] = 0;
        if (b == 13 && !(uW.cm.PrestigeModel.isPrestige(cityID) && uW.cm.PrestigeModel.getPrestigeFactionClass(cityID) == "druid")) city['Troop'+b+'Time'] = 0;
        if (b == 14 && !(uW.cm.PrestigeModel.isPrestige(cityID) && uW.cm.PrestigeModel.getPrestigeFactionClass(cityID) == "fey")) city['Troop'+b+'Time'] = 0;
        if (b == 15 && !(uW.cm.PrestigeModel.isPrestige(cityID) && uW.cm.PrestigeModel.getPrestigeFactionClass(cityID) == "briton")) city['Troop'+b+'Time'] = 0;
    }
    
    var def = [53,55,60,61,62];
    for (var i = 0; i < def.length; i++) {
        var fort = def[i];
        city['Def'+fort+'Time'] = WallsTrainTime(fort, 10000, cityID);
        if (fort == 53 && !(city.wallLevel > 5 && city.blacksmithLevel > 5 && city.fletchingLevel > 4)) city['Def'+fort+'Time']  = 0;
        if (fort == 55 && !(city.wallLevel > 7 && city.blacksmithLevel > 7 && city.fletchingLevel > 6 && city.geometryLevel > 6)) city['Def'+fort+'Time']  = 0;
        if (fort == 60 && !(city.wallLevel > 3 && city.blacksmithLevel > 3 && city.poisonedEdgeLevel > 1)) city['Def'+fort+'Time']  = 0;
        if (fort == 61 && !(city.wallLevel > 0 && city.metalAlloysLevel > 0)) city['Def'+fort+'Time']  = 0;
        if (fort == 62 && !(city.wallLevel > 1 && city.blacksmithLevel > 1 && city.loggingLevel > 1)) city['Def'+fort+'Time']  = 0;
    }

    return city;
}

// n -> Truppentyp, p -> Anzahl, city -> CityID
function TroopTrainTime(n, p, city) {
    if (p < 1) return 0;
    var h = +(uW.unitcost["unt" + n][7]) * p,
        c, f = {}, g = Seed.buildings["city" + city],
        b = {}, e = Seed.knights["city" + city],
        l, q = Seed.leaders["city" + city];
    f.barracks = 0;
    f.workshop = 0;
    f.stable = 0;
    f.tech = 0;
    f.knight = 0;
    f.ultimate = 0;
    for (var u in g) {
        var t = g[u];
        t.id = +(t[0]);
        t.level = +(t[1]);
        var s = (parseInt(n) == 13 || parseInt(n) == 14 || parseInt(n) == 15);
        t.isDruid = (parseInt(t[2]) >= 100 && parseInt(t[2]) <= 105);
        if ((t.id === 13 || t.id === 22 || t.id === 24 || t.id === 26) && t.level > 0) {
            if ((s && t.isDruid) || (!s && !t.isDruid)) {
                f.barracks += (t.level + 9)
            }
        }
        if (t.id === 16 && t.level > 0) {
            if (+(n) >= 9 && +(n) < 13) {
                f.workshop = t.level
            }
        }
        if (t.id === 17 && t.level > f.stable) {
            if (+(n) >= 7 && +(n) < 13) {
                f.stable = t.level
            }
        }
    }
    c = f.barracks / 10;
    h = Math.max(1, Math.ceil(h / c));
    c = 1;
    if (e) {
        l = e["knt" + q.combatKnightId];
        if (l) {
            f.knight = (+(l.combatBoostExpireUnixtime) - unixTime() > 0) ? (l.combat * 1.25) : l.combat
        } else {
            f.knight = 0
        }
    }
    if (Seed.tech) {
        f.tech = Seed.tech.tch5
    }
    f.ultimate = f.workshop + f.stable + f.tech;
    c = c * (1 + (0.1 * f.ultimate) + (0.005 * f.knight));
    var d = uW.cm.ThroneController.effectBonus(77);
    c = c * (1 + (d / 100));
    //Guardianbonus
    if (uW.cm.WorldSettings.isOn("GUARDIAN_MARCH_EFFECT")) {
        var SPD={0:0,1:1,2:1,3:2,4:2,5:3,6:3,7:4,8:5,9:7,10:10,11:20};
        var b1=0,y=false,v=false,w=0;
        var mm=Seed.guardian;
        for (var ii in mm) {
            var ww = mm[ii];
            if (ww.cityId==city) {
                if (ww.type== "stone") y=true;
                if (ww.guardianCount==4) v=true;
                var level=0;
                if (ww.cityGuardianLevels.stone!=undefined) level = ww.cityGuardianLevels.stone;
                //Server rechnen falsch! Client rechnet / 100
                w = SPD[level] / 10;
                var bx = 0;
                if (y && v) {
                    bx = 1.5;
                }
                if (y && !v) {
                    bx = 1;
                }
                if (!y && v) {
                    bx = 0.5;
                }
                if (!y && !v) {
                    bx = 0;
                }
                b1 = w * bx;
                c = c * (1 + b1)
            }
        }
    }
    h = Math.max(1, Math.ceil(h / c));
    
    if (uW.cm.PrestigeModel.isPrestige(city)) {
        var a = uW.cm.PrestigeModel.getPrestigeLevel(city);
        if (a > 0) {
            var m = uW.cm.WorldSettings.getSetting("ASCENSION_BARRACKS_BOOST"),
                k = JSON.parse(m),
                o = k.values[a - 1][1],
                i = parseFloat(o);
            h = Math.ceil(h * i)
        }
    }
    //Blessing DEATH_FROM_AFAR
    var r = uW.cm.BlessingSystemModel.isBlessingActive(uW.cm.BlessingSystemModel.getBlessing().DEATH_FROM_AFAR, city);
    if (n == 6 && r) {
        h = Math.ceil(h - (h * uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().DEATH_FROM_AFAR, city, {})))
    }
    //Blessing EXPEDITED_SENTENCING 
    h = Math.ceil(h - (h * uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().EXPEDITED_SENTENCING, city, {
        traintime: true,
        unitid: n,
    })));
    //Blessing TO_THE_FRONT_LINES
    h = Math.ceil(h - (h * uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().TO_THE_FRONT_LINES, city, {
        unitid: n,
    })));
    //Blessing PRIORITIZED_CONSTRUCTION
    h = Math.ceil(h - (h * uW.cm.BlessingSystemModel.applyBlessing(uW.cm.BlessingSystemModel.getBlessing().PRIORITIZED_CONSTRUCTION, city, {
        unittype: n,
    })));
    return h
}

// d -> Befestigungstyp, e -> Anzahl, city -> CityID
function WallsTrainTime(d, e, city) {
    var b = parseInt(parseInt(uW.fortcost["frt" + d][7])) * e;
    var f = 1;
    f += 0.1 * parseInt(Seed.tech.tch16);
    var a = 0;
    var c = Seed.knights["city" + city];
    if (c) {
        c = c["knt" + Seed.leaders["city" + city].politicsKnightId];
        if (c) {
            a = parseInt(c.combat);
            newkntlv = ((parseInt(c.politicsBoostExpireUnixtime) - unixTime()) > 0) ? (a * 1.25) : a;
            f = f + (0.005 * newkntlv)
        }
    }
    b = Math.max(1, Math.ceil(b / f));
    //Neue Forschungen
    if (typeof Seed.tech2 !== "undefined") {
        if (typeof Seed.tech2.tch3 !== "undefined") {
            var c = (1 - parseFloat(Seed.tech2.tch3) * 0.05);
            b = Math.max(1, Math.ceil(b * c));
        }
    }
    return b
}

function setCities(){
    var il = unsafeWindow.itemlist;
    for (var i=1101; i < 1115; i++)
        crestname[i] = il['i'+i].name
    getResearchLevels();
    Cities.numCities = Seed.cities.length;
    Cities.cities = [];
    Cities.byID = {};
    for (i=0; i<Cities.numCities; i++){
        city = {};
        city.idx = i;
        city.id = parseInt(Seed.cities[i][0]);
        city.name = Seed.cities[i][1];
        city.x = parseInt(Seed.cities[i][2]);
        city.y = parseInt(Seed.cities[i][3]);
        city.tileId = parseInt(Seed.cities[i][5]);
        city.provId = parseInt(Seed.cities[i][4]);
        getTroopDefTrainEstimates('city'+ city.id, city.id);
        Cities.cities[i] = city;
        Cities.byID[Seed.cities[i][0]] = city;
    }
}

function officerId2String (oid){
    if (oid==null)
        return '';
    else if (oid==3)
        return unsafeWindow.allianceOfficerTypeMapping[3];
    else if (oid==2)
        return unsafeWindow.allianceOfficerTypeMapping[2];
    else if (oid==1)
        return unsafeWindow.allianceOfficerTypeMapping[1];
    else if (oid==4)
        return unsafeWindow.allianceOfficerTypeMapping[4];
    return '';
}


//<editor-fold desc="SPLIT:CollectGold.js">
/************************************************************************************
 *                        KOC POWER - GOLD COLLECTOR                                    *
 ************************************************************************************/
var CollectGold = {
    timer : null,
    lastCollect : {},

    init : function (){
        var t = CollectGold;
        for (var c=0; c<Cities.numCities; c++)
            t.lastCollect['c'+ Cities.cities[c].id] = 0;
        if (Options.pbGoldEnable)
            t.setEnable (true);
    },

    setEnable : function (tf){
        var t = CollectGold;
        clearTimeout (t.timer);
        if (tf)
            t.tick();
    },

    colCityName : null,
    colHappy : 0,
    tick : function (){
        var t = CollectGold;
        for (var c=0; c<Cities.numCities; c++){
            var city = Cities.cities[c];
            var happy = Seed.citystats['city'+ city.id].pop[2];
            var since = unixTime() - t.lastCollect['c'+city.id];
            if (happy>=Options.pbGoldHappy && since>15*60){
                t.lastCollect['c'+city.id] = unixTime();
                t.colCityName = city.name;
                t.colHappy = happy;
                t.ajaxCollectGold (city, t.e_ajaxDone);
                break;
            }
        }
        t.timer = setTimeout (t.tick, 60000);
    },

    e_ajaxDone : function (rslt){
        var t = CollectGold;
    },

    ajaxCollectGold : function (city, notify){
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.cid = city.id;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/levyGold.php" + unsafeWindow.g_ajaxsuffix, {
            method: "post",
            parameters: params,
            onSuccess: function (rslt) {
                if (notify)
                    notify (rslt);
            },
            onFailure: function (rslt) {
                if (notify)
                    notify (rslt);
            }
        });
    },
}
//</editor-fold>

var gmtClock = {
    span : null,
    timer : null,

    init : function (){
        var t = gmtClock;

        t.setEnable (Options.gmtClock);
    },

    setEnable : function (tf){
        var t = gmtClock;
        clearInterval (t.timer);
        if (Options.gmtClock){
            t.timer = setInterval (t.everySecond, 2000);
            t.span = document.createElement ('span');
            t.span.style.fontWeight = 'bold';
            ById('kochead_time').style.display='none';
            ById('kochead_time').parentNode.appendChild (t.span);
        } else {
            if (t.span!=null) t.span.innerHTML = '';
            ById('kochead_time').style.display='';

        }
    },
    everySecond : function (){
        var t = gmtClock;
        var now = new Date();
        now.setTime(now.getTime() + (now.getTimezoneOffset()*60000));
        t.span.innerHTML = ' '+ now.toLocaleFormat('%H:%M:%S') +'';
    },
}

//<editor-fold desc="SPLIT:RefreshEvery.js">
/************************************************************************************
 *                        KOC POWER - AUTO REFRESH                                    *
 ************************************************************************************/
var RefreshEvery  = {
    timer : null,
    PaintTimer : null,
    NextRefresh : 0,
    box : null,
    target : null,

    init : function (){
        var t = RefreshEvery;
        t.creatediv();
        if (Options.pbEveryMins < 1)
            Options.pbEveryMins = 1;
        RefreshEvery.setEnable (Options.pbEveryEnable);
    },

    creatediv : function(){
        var t = RefreshEvery;
        t.target = ById('comm_tabs');
        if(t.target == null){
            setTimeout(t.creatediv, 2000);
            return;
        }
        t.box = document.createElement('div');
        t.target.appendChild(t.box);
    },

    setEnable : function (tf){
        var t = RefreshEvery;
        clearTimeout (t.timer);
        if (tf) {
            //t.timer = setTimeout (t.doit, Options.pbEveryMins*60000);
            t.NextRefresh = unixTime() + (Options.pbEveryMins*60);
            t.timer = setTimeout (t.Paint, 5000);
        } else {
            //t.PaintTimer = null;
            t.timer = null;
            t.NextRefresh = 0;
            t.box.innerHTML = '<div style="color:#141516;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' <span class="boldRed">(</span>' + getServerId() +'<span class="boldRed">)</span></div>';
        }
    },

    doit : function (){
        actionLog(""+culang.logSelectMoreError+"", ""+culang.refreshActionLog+" "+culang.refreshActionLog2+" <font color=res>"+ Options.pbEveryMins +"</font> "+culang.refreshActionLog3+"");
        reloadKOC();
    },

    setTimer : function (){
        var t = RefreshEvery;
        clearTimeout (t.timer);
        if (Options.pbEveryMins < 1) Options.pbEveryMins = 1;
        RefreshEvery.setEnable (Options.pbEveryEnable);
    },

    Paint : function(){
        var t = RefreshEvery;
        if(t.timer == null) return;
        now = unixTime();
        var text = '';
        var Left = parseInt(t.NextRefresh - now);
        if ( Left < 0){
            Left = 0;
            t.doit();
        }
        if ( Left < 60) text += '<div style="color:#141516;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' (<span class="boldRed">' + getServerId() +'</span>) - <span id="KsTaref" title="'+culang.refreshNowNote+'">'+culang.refreshReload+'</span> '+culang.refreshIn+' <FONT color=red><span id="KsTaTim" title="'+culang.refreshResetNote+'">'+ timestr(Left) +'</span></div> </div>';
        else text += '<div style="color:#141516;text-shadow: 1px 1px 1px #AAA;font-variant:small-caps;font-weight:bold;">&nbsp;&nbsp;&nbsp;&nbsp;'+ getMyAlliance()[1] + ' (<span class="boldRed">' + getServerId() +'</span>) - <span id="KsTaref" title="'+culang.refreshNowNote+'">'+culang.refreshReload+'</span> '+culang.refreshIn+' <span id="KsTaTim" title="'+culang.refreshResetNote+'">'+ timestr(Left) +'</span></div> </div>';

        t.box.innerHTML = text;

        ById('KsTaref').addEventListener ('click', t.doit, false);
        ById('KsTaTim').addEventListener ('click', function() { t.setEnable(true); }, false);
        t.timer = setTimeout (t.Paint, 5000);
    },
}
//</editor-fold>

var FairieKiller  = {
    saveFunc : null,
    init : function (tf){
        FairieKiller.saveFunc = unsafeWindow.Modal.showModalUEP;
        FairieKiller.setEnable (tf);
    },
    setEnable : function (tf){
        if (tf)
            unsafeWindow.Modal.showModalUEP = eval ('function FairieKiller (a,b,c) {logit("Blocked Faire popup");}');
        else
            unsafeWindow.Modal.showModalUEP = FairieKiller.saveFunc;
    },
}
function KOCnotFound(secs){
    var div;
    var countdownTimer = null;
    var endSecs = (new Date().getTime()/1000) + secs;

    div = document.createElement('div');
    div.innerHTML = '<DIV style="font-size:18px; background-color:#a00; color:#fff"><CENTER><BR>'+culang.kocNotFound+'<BR>\
      '+culang.refreshIn+' <SPAN id=pbwdsecs></span><BR><INPUT id=pbwdcan type=submit value="'+culang.mainCancel+'"><BR><BR></div>';
    document.body.insertBefore (div, document.body.firstChild);
    ById('pbwdcan').addEventListener('click', cancel, false);
    countdown();

    function countdown (){
        var secsLeft = endSecs - (new Date().getTime()/1000);
        ById('pbwdsecs').innerHTML = timestr(secsLeft);
        if (secsLeft < 0)
            reloadKOC();
        countdownTimer = setTimeout (countdown, 1000);
    }
    function cancel (){
        clearTimeout (countdownTimer);
        document.body.removeChild (div);
    }
}

var WideScreen = {
    chatIsRight : false,
    useWideMap : false,
    rail : null,

    init : function (){
        t = WideScreen;
        if (GlobalOptions.pbWideScreen){
            t.rail = searchDOM (ById('mod_maparea'), 'node.className=="maparea_rrail"', 10);
            GM_addStyle ('.modalCurtain {width:760px !important} .mod_comm_mmb{z-index:0 !important}');
            try {
                ById('progressBar').parentNode.removeChild(ById('progressBar'));
                ById('crossPromoBarContainer').parentNode.removeChild(ById('crossPromoBarContainer'));
            } catch (e) {
            }
        }
    },

    setChatOnRight : function (tf){
        t = WideScreen;
        if (tf == t.chatIsRight || !GlobalOptions.pbWideScreen)
            return;
        if (tf){
            var chat = ById('kocmain_bottom').childNodes[1];
            if (!chat || chat.className!='mod_comm')
                setTimeout (function (){t.setChatOnRight(tf)}, 1000);
            chat.style.top = '-624px';
            chat.style.left = '760px';
            chat.style.height = '720px';
            chat.style.background = 'url("'+ CHAT_BG_IMAGE +'")';
            ById('mod_comm_list1').style.height = '580px';
            ById('mod_comm_list2').style.height = '580px';
        } else {
            var chat = ById('kocmain_bottom').childNodes[1];
            chat.style.top = '0px';
            chat.style.left = '0px';
            chat.style.height = '';
            chat.style.background = '';
            ById('mod_comm_list1').style.height = '287px';
            ById('mod_comm_list2').style.height = '287px';
        }
        t.chatIsRight = tf;
    },

    useWideMap : function (tf) {
        t = WideScreen;
        if (tf == t.useWideMap || !GlobalOptions.pbWideScreen)
            return;
        if (tf){
            t.rail.style.display = 'none';
            ById('mapwindow').style.height = "436px";
            ById('mapwindow').style.width = "1220px";
            ById('mapwindow').style.zIndex = "50";
        } else {
            t.rail.style.display = 'block';
            ById('mapwindow').style.height = "439px";
            ById('mapwindow').style.width = "760px";
            ById('mapwindow').style.zIndex = "";
        }
    },
}

function DoUnsafeWindow(func, execute_by_embed) {
    if(this.isChrome || execute_by_embed) {
        var scr=document.createElement('script');
        scr.innerHTML=func;
        document.body.appendChild(scr);
    } else {
        try {
            eval("unsafeWindow."+func);
        } catch (error) {
            logit("A javascript error has occurred when executing a function via DoUnsafeWindow. Error description: "+error.description);
        }
    }
}
function GetDisplayName(){
    var DisplayName = ById('topnavDisplayName');
    if(DisplayName){
        DisplayName = DisplayName.innerHTML;
    }else{
        DisplayName = null;
    }
    return DisplayName;
}
var ChatPane = {
    timer:null,

    init : function(){
        var t = ChatPane;
        if(Options.HelpRequest || Options.ChatRules || Options.DeleteRequest){
            t.timer=setInterval(t.HandleChatPane, 2500);
        }
    },

    HandleChatPane : function() {
        var DisplayName = GetDisplayName();

        var AllianceChatBox=ById('mod_comm_list2');

        if(AllianceChatBox){
            var chatPosts = document.evaluate(".//div[contains(@class,'chatwrap')]", AllianceChatBox, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );

            if(chatPosts){
                for (var i = 0; i < chatPosts.snapshotLength; i++) {
                    thisPost = chatPosts.snapshotItem(i);
                    if(Options.HelpRequest){

                        var postAuthor = document.evaluate('.//*[contains(@class,"nm")]', thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
                        if(postAuthor.snapshotItem(0)){
                            var postAuthorName = postAuthor.snapshotItem(0).innerHTML;

                            if(postAuthorName != DisplayName){

                                var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
                                if(helpAllianceLinks){
                                    for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
                                        thisLink = helpAllianceLinks.snapshotItem(j);
                                        var alreadyClicked = thisLink.getAttribute("clicked");
                                        if(!alreadyClicked){
                                            thisLink.setAttribute('clicked', 'true');
                                            var myregexp = /(claimAllianceChatHelp\(.*\);)/;
                                            var match = myregexp.exec(thisLink.getAttribute("onclick"));

                                            if (match != null) {
                                                onclickCode = match[0];
                                                if(true){
                                                    DoUnsafeWindow(onclickCode);
                                                }
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                    if(Options.ChatRules){
                        var myregexp1 = culang.getChatRules;
                        if (thisPost.innerHTML.match(myregexp1)) {
                            thisPost.parentNode.removeChild(thisPost);
                        }
                    }
                    if(Options.DeleteRequest){
                        var helpAllianceLinks=document.evaluate(".//a[contains(@onclick,'claimAllianceChatHelp')]", thisPost, null, XPathResult.UNORDERED_NODE_SNAPSHOT_TYPE, null );
                        if(helpAllianceLinks){
                            for (var j = 0; j < helpAllianceLinks.snapshotLength; j++) {
                                thisLink = helpAllianceLinks.snapshotItem(j);
                                thisLink.parentNode.parentNode.parentNode.parentNode.parentNode.removeChild(thisLink.parentNode.parentNode.parentNode.parentNode);
                            }
                        }
                        var myregexp1 = culang.secondregexp1;
                        var myregexp2 = culang.secondregexp2;
                        var myregexp3 = culang.secondregexp3;
                        var myregexp4 = culang.secondregexp4;
                        if (
                            thisPost.innerHTML.match(myregexp1) ||
                            thisPost.innerHTML.match(myregexp2) ||
                            thisPost.innerHTML.match(myregexp3) ||
                            thisPost.innerHTML.match(myregexp4) ||
                            thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern1) ||
                            thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern2) ||
                            thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern3) ||
                            thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern4) ||
                            thisPost.innerHTML.match(SR.en.RemoveChatMessagePattern5) ||
                            thisPost.innerHTML.match(/Du bist der # [0-9]+\. von 10 Helfern f.r .+ .+!/) ||
                            thisPost.innerHTML.match(/Du hast .+ bei dem .+ Projekt bereits geholfen./ )
                            ) {
                            if(thisPost.parentNode!==null) //TODO review error "thisPost.parentNode is null"
                                thisPost.parentNode.removeChild(thisPost);
                        }
                        var myregexp1 = culang.myregexp1;
                        var myregexp2 = culang.myregexp2;
                        var myregexp3 = culang.myregexp3;
                        var myregexp4 = culang.myregexp4;
                        var myregexp5 = culang.myregexp5;
                        if (thisPost.innerHTML.match(myregexp1) || thisPost.innerHTML.match(myregexp2) || thisPost.innerHTML.match(myregexp3) || thisPost.innerHTML.match(myregexp4) || thisPost.innerHTML.match(myregexp5)) {
                            if(thisPost.parentNode!==null) //TODO review error "thisPost.parentNode is null"
                                thisPost.parentNode.removeChild(thisPost);
                        }
                    }
                }
            }
        }
    },

}

String.prototype.StripQuotes = function () {
    return this.replace(/"/g, '');
};

function entier_1dec (nombre){
    if (parseInt(nombre*10)!=0){
        return parseInt(nombre*10)/10;
    } else {
        return nombre;
    }
}

var tileNames = {
    'city' : culang.mainCity,
    'lake' : culang.kocLake,
    'grassland' : culang.kocGrassland,
    'plain' : culang.kocPlain,
    'woods' : culang.kocForests,
    'hills' : culang.kocHill,
    'mountain' : culang.kocMount,
    'bog' : culang.kocBog,
    'bcity' : culang.kocBarbarianCamps,
    'boss' : culang.kocDarkForest,
}
function DrawLevelIcons() {
    var maptileRe = /modal_maptile.([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+),([^,]+)/;
    var mapwindow = document.getElementById('mapwindow');
    if (!mapwindow) return;
    var levelIcons = document.getElementById('levelIcons');
    if (levelIcons) return;

    var ss = document.evaluate(".//a[contains(@class,'slot')]", mapwindow, null, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null);
    var idDone = false;
    for (var s = 0; s < ss.snapshotLength; s++) {
        var a = ss.snapshotItem(s);
        var onclick = a.getAttribute('id');
        //alert(onclick);
        var owner = '';
        if (onclick) {
            // logit(onclick);
            var tileinfo = uW.g_mapObject.model.getTileActions(onclick)["tileClick"];
            //logit(inspect(tileinfo));
            if (tileinfo) {
                var might = parseInt(tileinfo.might);
                var alliance = parseIntNan(tileinfo.allianceId);
                var dip = getDiplomacy(alliance);
                var province = uW.provincenames['p'+ tileinfo.province]
                owner = tileinfo.username;
            }
        }
        var sp = a.getElementsByTagName('span');
        if (sp.length == 0) continue;

        if (!idDone) {
            a.id = 'levelIcons';
            idDone = true;
        }
        sp[0].style.color = 'white';
        sp[0].style.fontSize = '10px';
        sp[0].style.textShadow = '0.2em 0.2em 0.1em black';

        if (Options.MapShowExtra) {
            if (tileinfo.username != "null") {
                if (tileinfo.alliance != null) {
                    if (dip == culang.kocHostile) sp[0].style.color = 'red';
                    sp[0].innerHTML = 'Lvl: ' + tileinfo.level + ' / ' + province + '<br>' + owner + '<br>' + addCommas(might) +'<br>'+tileinfo.alliance;
                } else {
                    sp[0].style.color = 'yellow';
                    sp[0].innerHTML = 'Lvl: ' + tileinfo.level + ' / ' + province + '<br>' + owner + '<br>' + addCommas(might);
                }
            } else 
                sp[0].innerHTML = 'Lvl: ' + tileinfo.level + ' / ' + province;
        } 
    }
}

function GetProvince(x,y){
    if(x>=  0 && x<=149 && y>=  0 && y<=149) return "Tintagel";
    if(x>=150 && x<=299 && y>=  0 && y<=149) return "Cornwall";
    if(x>=300 && x<=449 && y>=  0 && y<=149) return "Astolat";
    if(x>=450 && x<=599 && y>=  0 && y<=149) return "Lyonesse";
    if(x>=  0 && x<=149 && y>=150 && y<=299) return "Paimpont";
    if(x>=150 && x<=299 && y>=150 && y<=299) return "Cameliard";
    if(x>=300 && x<=449 && y>=150 && y<=299) return "Sarras";
    if(x>=450 && x<=599 && y>=150 && y<=249) return "Canoel";
    if(x>=600 && x<=749 && y>=150 && y<=299) return "Avalon";
    if(x>=  0 && x<=149 && y>=300 && y<=449) return "Carmathen";
    if(x>=150 && x<=299 && y>=300 && y<=449) return "Shallott";
    if(x>=450 && x<=599 && y>=300 && y<=449) return "Cadbury";
    if(x>=600 && x<=749 && y>=300 && y<=449) return "Glastonbury";
    if(x>=  0 && x<=149 && y>=450 && y<=599) return "Camlann";
    if(x>=150 && x<=299 && y>=450 && y<=599) return "Orkney";
    if(x>=300 && x<=449 && y>=450 && y<=599) return "Dore";
    if(x>=150 && x<=299 && y>=  0 && y<=149) return "Cornwall";
    if(x>=450 && x<=599 && y>=450 && y<=599) return "Logres";
    if(x>=600 && x<=749 && y>=450 && y<=599) return "Caerleon";
    if(x>=  0 && x<=149 && y>=600 && y<=749) return "Parmenie";
    if(x>=150 && x<=299 && y>=600 && y<=749) return "BodminMoor";
    if(x>=300 && x<=449 && y>=600 && y<=749) return "Cellwig";
    if(x>=450 && x<=599 && y>=600 && y<=749) return "Listeneise";
    if(x>=600 && x<=749 && y>=600 && y<=749) return "Albion";
    else return "?"
}

function CdispCityPicker (id, span, dispName, notify, selbut, disable_list){
    function CcityButHandler (t){
        var that = t;
        this.clickedCityBut = clickedCityBut;
        function clickedCityBut (e){
            if (that.selected != null)
                that.selected.className = "castleBut castleButNon";
            that.city = Cities.cities[e.target.id.substr(that.prefixLen)];
            if (that.dispName)
                ById(that.id+'cname').innerHTML = that.city.name;
            e.target.className = "castleBut castleButSel";
            that.selected = e.target;
            if (that.coordBoxX){
                that.coordBoxX.value = that.city.x;
                that.coordBoxY.value = that.city.y;
                that.coordBoxX.style.backgroundColor = '#ffffff';
                that.coordBoxY.style.backgroundColor = '#ffffff';
            }
            if (that.notify != null)
                that.notify(that.city, that.city.x, that.city.y);
        }
    }

    function selectBut (idx){
        ById(this.id+'_'+idx).click();
    }

    function bindToXYboxes (eX, eY){
        function CboxHandler (t){
            var that = t;
            this.eventChange = eventChange;
            if (that.city){
                eX.value = that.city.x;
                eY.value = that.city.y;
            }
            function eventChange (){
                var xValue=that.coordBoxX.value.trim();
                var xI=/^\s*([0-9]+)[\s,]+([0-9]+)/.exec(xValue);
                if(xI) {
                    that.coordBoxX.value=xI[1]
                    that.coordBoxY.value=xI[2]
                }
                var x = parseInt(that.coordBoxX.value, 10);
                var y = parseInt(that.coordBoxY.value, 10);
                if (isNaN(x) || x<0 || x>750){
                    that.coordBoxX.style.backgroundColor = '#ff8888';
                    return;
                }
                if (isNaN(y) || y<0 || y>750){
                    that.coordBoxY.style.backgroundColor = '#ff8888';
                    return;
                }
                that.coordBoxX.style.backgroundColor = '#ffffff';
                that.coordBoxY.style.backgroundColor = '#ffffff';
                if (that.notify != null)
                    that.notify (null, x, y);
            }
        }
        this.coordBoxX = eX;
        this.coordBoxY = eY;
        var bh = new CboxHandler(this);
        eX.size=2;
        eX.maxLength=10;
        eY.size=2;
        eY.maxLength=3;
        eX.addEventListener('change', bh.eventChange, false);
        eY.addEventListener('change', bh.eventChange, false);
    }

    this.selectBut = selectBut;
    this.bindToXYboxes = bindToXYboxes;
    this.coordBoxX = null;
    this.coordBoxY = null;
    this.id = id;
    this.dispName = dispName;
    this.prefixLen = id.length+1;
    this.notify = notify;
    this.selected = null;
    this.city = null;
    var m = '';
    for (var i=0; i<Cities.cities.length; i++){
        if(matTypeof(disable_list) == 'array'){
            if(disable_list[i])
                m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit DISABLED \>';
            else
                m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit \>';
        } else
            m += '<INPUT class="castleBut castleButNon" id="'+ id +'_'+ i +'" value="'+ (i+1) +'" type=submit \>';
    }
    if (dispName)
        m += ' &nbsp; <SPAN style="display:inline-block; width:85px; font-weight:bold;" id='+ id +'cname' +'></span>';
    span.innerHTML = m;
    var handler = new CcityButHandler(this);
    for (var i=0; i<Cities.cities.length; i++)
        document.getElementById (id+'_'+i).addEventListener('click', handler.clickedCityBut, false);
    if (selbut != null)
        this.selectBut(selbut);
}

var pop = null;

function dialogRetry (errMsg, seconds, onRetry, onCancel, errCode){
    seconds = parseInt(seconds);
    if (pop == null) {
        pop = new CPopup ('Ksptretry', 0, 0, 400,300, true);

        pop.getTopDiv().innerHTML = '<div class="popupBanner">'+ScriptName+'</div>';
        pop.getMainDiv().innerHTML = '<CENTER><BR><FONT COLOR=#550000><B>'+culang.multiErrorPopup+'</b></font><BR><BR><DIV id=KsparetryErrMsg></div>\
         <BR><BR><B>'+culang.kocDialogRetry+' <SPAN id=KsparetrySeconds></b></span> '+culang.mainSeconds+' ...<BR><INPUT id=KsparetryCancel type=submit value="'+culang.mainCancel+'" \>';
        ById('KsparetryCancel').addEventListener ('click', doCancel, false);

    }
    pop.show(true);
    pop.centerMe(mainPop.getMainDiv());
    /*if(errCode && unsafeWindow.g_js_strings.errorcode['err_'+errCode]) {
     if (document.getElementById('BOparetryErrMsg')) {
     if (uW.g_js_strings.errorcode['err_'+errCode]) 
     document.getElementById('BOparetryErrMsg').innerHTML = uW.g_js_strings.errorcode['err_'+errCode];
     else
     document.getElementById('BOparetryErrMsg').innerHTML ="Erreur : "+ errMsg;
     }
     } else
     if (document.getElementById('BOparetryErrMsg')) document.getElementById('BOparetryErrMsg').innerHTML = errMsg;*/
    if(errCode && unsafeWindow.g_js_strings.errorcode['err_'+errCode])
        if (ById('KsparetryErrMsg')) ById('KsparetryErrMsg').innerHTML = unsafeWindow.g_js_strings.errorcode['err_'+errCode];
        else
            document.getElementById('KsparetryErrMsg').innerHTML = errMsg;
    if (document.getElementById('KsparetrySeconds')) document.getElementById('KsparetrySeconds').innerHTML = seconds;
    var rTimer = setTimeout (doRetry, seconds*1000);
    countdown ();

    function countdown (){
        if (document.getElementById('KsparetrySeconds')) ById('KsparetrySeconds').innerHTML = seconds--;
        if (seconds > 0)
            cdTimer = setTimeout (countdown, 1000);
    }
    function doCancel(){
        clearTimeout (rTimer);
        clearTimeout (cdTimer);
        pop.destroy();
        onCancel ();
    }
    function doRetry (){
        clearTimeout (rTimer);
        clearTimeout (cdTimer);
        pop.show(false);
        onRetry();
    }
}

function GM_AjaxGet (url, args, notify, label){
    GM_xmlhttpRequest({
        method: "get",
        url: addUrlArgs(url, args),
        onload: function (rslt) {
            notify (rslt.responseText);
        },
        onerror: function () {
            notify (null);
        },
    });
}

function GM_AjaxPost (url, args, notify, label){
    GM_xmlhttpRequest({
        method: "post",
        url: url,
        data: implodeUrlArgs(args),
        headers: {     "Content-Type": "application/x-www-form-urlencoded", 
                                'X-Requested-With': 'XMLHttpRequest', 
                                'X-Prototype-Version': '1.6.1',
                                'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
                            },
        onload: function (rslt) {
            notify (rslt.responseText);
        },
        onerror: function () {
            notify (null);
        },
    });
}
function AjaxRequest (url, opts){
    var headers = {
        'X-Requested-With': 'XMLHttpRequest',
        'X-Prototype-Version': '1.6.1',
        'Accept': 'text/javascript, text/html, application/xml, text/xml, */*',
    };
    var ajax = null;

    if (window.XMLHttpRequest)
        ajax=new XMLHttpRequest();
    else
        ajax=new ActiveXObject("Microsoft.XMLHTTP");

    if (opts.method==null || opts.method=='')
        method = 'GET';
    else
        method = opts.method.toUpperCase();

    if (method == 'POST'){
        headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    } else if (method == 'GET'){
        addUrlArgs (url, opts.parameters);
    }

    ajax.onreadystatechange = function(){
        if (ajax.readyState==4) {
            if (ajax.status >= 200 && ajax.status < 305)
                if (opts.onSuccess) opts.onSuccess(ajax);
                else
                if (opts.onFailure) opts.onFailure(ajax);
        } else {
            if (opts.onChange) opts.onChange (ajax);
        }
    }
    ajax.open(method, url, true);
    for (var k in headers)
        ajax.setRequestHeader (k, headers[k]);
    if (matTypeof(opts.requestHeaders)=='object')
        for (var k in opts.requestHeaders)
            ajax.setRequestHeader (k, opts.requestHeaders[k]);

    if (method == 'POST'){
        var a = [];
        for (k in opts.parameters){
            if(matTypeof(opts.parameters[k]) == 'object')
                for(var h in opts.parameters[k])
                    a.push (k+'['+h+'] ='+ opts.parameters[k][h] );
            else
                a.push (k +'='+ opts.parameters[k] );
        }
        ajax.send (a.join ('&'));
    } else               {
        ajax.send();
    }
}
function getOffset( el ) {
    var _x = 0;
    var _y = 0;
    while( el && !isNaN( el.offsetLeft ) && !isNaN( el.offsetTop ) ) {
        _x += el.offsetLeft - el.scrollLeft;
        _y += el.offsetTop - el.scrollTop;
        el = el.offsetParent;
    }
    return { top: _y, left: _x };
}

function implodeUrlArgs (obj){
    var a = [];
    for (var k in obj)
        a.push (k +'='+ encodeURI(obj[k]) );
    return a.join ('&');
}
function addUrlArgs (url, args){
    if (!args)
        return url;
    if (url.indexOf('?') < 0)
        url += '?';
    else if (url.substr(url.length-1) != '&')
        url += '&';
    if (matTypeof(args == 'object'))
        return url + implodeUrlArgs (args);
    return url + args;
}
function AjaxRequest2 (url, opts){
    var headers = {
        'X-Requested-With': 'XMLHttpRequest',
        'X-Prototype-Version': '1.6.1',
        'Accept': 'text/javascript, text/html, application/xml, text/xml, */*'
    };
    var ajax = null;
    if (window.XMLHttpRequest)
        ajax=new XMLHttpRequest();
    else
        ajax=new ActiveXObject("Microsoft.XMLHTTP");
    if (opts.method==null || opts.method=='')
        method = 'GET';
    else
        method = opts.method.toUpperCase();
    if (method == 'POST'){
        headers['Content-type'] = 'application/x-www-form-urlencoded; charset=UTF-8';
    } else if (method == 'GET'){
        addUrlArgs (url, opts.parameters);
    }
    ajax.onreadystatechange = function(){
        if (ajax.readyState==4) {
            if (ajax.status >= 200 && ajax.status < 305)
                if (opts.onSuccess) opts.onSuccess(ajax);
                else
                if (opts.onFailure) opts.onFailure(ajax);
        } else {
            if (opts.onChange) opts.onChange (ajax);
        }
    }
    ajax.open(method, url, true);
    for (var k in headers)
        ajax.setRequestHeader (k, headers[k]);
    if (matTypeof(opts.requestHeaders)=='object')
        for (var k in opts.requestHeaders)
            ajax.setRequestHeader (k, opts.requestHeaders[k]);
    if (method == 'POST'){
        var a = [];
        for (k in opts.parameters){
            if(matTypeof(opts.parameters[k]) == 'object'){
                for(var h in opts.parameters[k]){
                    if(matTypeof(opts.parameters[k][h]) == 'object'){
                        for(var i in opts.parameters[k][h]){
                            if(matTypeof(opts.parameters[k][h][i]) == 'object'){
                                for(var j in opts.parameters[k][h][i]){
                                    a.push (k+'['+h+']['+i+']['+j+'] ='+ opts.parameters[k][h][i][j] );
                                }
                            } else
                                a.push (k+'['+h+']['+i+']'+' ='+ opts.parameters[k][h][i]);
                        }
                    } else
                        a.push (k+'['+h+'] ='+ opts.parameters[k][h] );
                }
            } else
                a.push (k +'='+ opts.parameters[k] );
        }
        ajax.send (a.join ('&'));
    } else {
        ajax.send();
    }
}
function MyAjaxRequest (url, o, noRetryX){
    var opts = unsafeWindow.Object.clone(o);
    var wasSuccess = o.onSuccess;
    var wasFailure = o.onFailure;
    var retry = 0;
    var delay = 3;
    var show=true;
    var silentTimer;
    var noRetry = noRetry===true?true:false;
    opts.onSuccess = mySuccess;
    opts.onFailure = myFailure;
    new AjaxRequest(url, opts);
    return;

    function myRetry(){
        ++retry;
        if (retry>5) {
            actionLog(""+culang.logSelectMoreError+"", "<font color=res>"+culang.errorQuery+"</font>");
            return false;
        }
        new AjaxRequest(url, opts);

        delay = delay * 1.20;
    }
    function myFailure(){
        var o = {};
        o.ok = false;
        o.errorMsg = "AJAX Communication Failure";
        wasFailure (o);
    }
    function mySuccess (msg){
        //logit(msg);
        var rslt;
        try {
            rslt = JSON2.parse(msg.responseText);
        } catch(e) {

            if (retry<2) {
                rslt = {"ok":false,"error_code":9,"errorMsg":"Failed due to invalid json"}
            } else {
                rslt = {"ok":true,"error_code":9,"data":[], "json": msg,};
            }
            actionLog(""+culang.logSelectMoreError+"", "JSON-Error: "+msg.responseText);
        }
        var x;
        /*
        if (window.EmulateAjaxError){
            rslt.ok = false;
            rslt.error_code=8;
        }
        */
        if (rslt.ok){
            if (rslt.updateSeed) {
                try {
                    unsafeWindow.update_seed(rslt.updateSeed);
                } catch (e) {}
            }
            wasSuccess (rslt);
            return;
        }

        rslt.errorMsg = unsafeWindow.printLocalError((rslt.error_code || null), (rslt.msg || null), (rslt.feedback || null));

        if (!noRetry && (rslt.error_code==0 ||rslt.error_code==8 || rslt.error_code==1 || rslt.error_code==3)){
            actionLog(culang.mainError, "<font color=res>"+ msg.responseText +"</font>");
            dialogRetry (inspect(rslt.errorMsg), delay, function(){myRetry()}, function(){wasSuccess (rslt)}, rslt.error_code);
        } else if (!noRetry && rslt.error_code==9) {
            silentTimer = setTimeout(silentRetry, delay*100);
        } else {
            wasSuccess (rslt);
        }
    }
    function silentRetry() {
        clearTimeout(silentTimer);
        myRetry();
    }
}

function getDiplomacy (aid) {
    if (Seed.allianceDiplomacies == null)
        return ''+culang.kocNeutral+'';
    if (Seed.allianceDiplomacies.friendly && Seed.allianceDiplomacies.friendly['a'+aid] != null)
        return ''+culang.kocFriendly+'';
    if (Seed.allianceDiplomacies.hostile && Seed.allianceDiplomacies.hostile['a'+aid] != null)
        return ''+culang.kocHostile+'';
    if (aid == Seed.allianceDiplomacies.allianceId)
        return ''+culang.kocAllys+'';
    return ''+culang.kocNeutral+'';
};

function getMyUserId (){return parseInt([Seed.tutorial.userId]);}
function getMyAlliance (){
    if (Seed.allianceDiplomacies==null || Seed.allianceDiplomacies.allianceName==null)
        return [0, ''+culang.mainNone+''];
    else
        return [Seed.allianceDiplomacies.allianceId, Seed.allianceDiplomacies.allianceName];
}
function UniteKMG(nb) {
    if (Math.abs(nb)>1000000000)
        val="<span title='"+addCommas(nb)+"'>" + addCommas((nb/1000000000).toFixed(2)) +" "+culang.shortBillion+"</span>";
    else if (Math.abs(nb)>1000000)
        val="<span title='"+addCommas(nb)+"'>" + addCommas((nb/1000000).toFixed(2)) +" "+culang.shortMillion+"</span>";
    else if (nb==0)
        val="0";
    else
        val=addCommas(nb);

    return val;
}

function getMarchInfoBOT(cityID){
    var ret = {};
    ret.marchUnits = [];
    ret.returnUnits = [];
    ret.resources = [];
    for (i=0; i<16; i++){
        ret.marchUnits[i] = 0;
        ret.returnUnits[i] = 0;
    }
    for (i=0; i<6; i++){
        ret.resources[i] = 0;
    }
    for (k in Seed.queue_atkp[cityID]){
        march = Seed.queue_atkp[cityID][k];
        if(march.marchType != 5){
            if (typeof (march) == 'object'){
                for (ii=0; ii<16; ii++){
                    ret.marchUnits[ii] += parseInt (march['unit'+ ii +'Count']);
                    ret.returnUnits[ii] += parseInt (march['unit'+ ii +'Return']);
                }
                for (ii=1; ii<6; ii++){
                    if (march['r'+ ii] && parseInt(march['r'+ ii]) > 0) {
                        ret.resources[ii] += parseInt(march['r'+ ii]);
                    } else {
                        ret.resources[ii] += parseInt(march['resource'+ ii]);
                    }
                }
                if (march['g'] && parseInt(march['g']) > 0) {
                    ret.resources[0] += parseInt(march['g']);
                } else {
                    ret.resources[0] += parseInt(march['gold']);
                }
            }
        }
    }
    return ret;
}

function getMarchInfo (){
    var ret = {};
    ret.marchUnits = [];
    ret.returnUnits = [];
    ret.resources = [];
    for (i=0; i<16; i++){
        ret.marchUnits[i] = 0;
        ret.returnUnits[i] = 0;
    }
    for (i=0; i<6; i++){
        ret.resources[i] = 0;
    }
    var now = unixTime();
    for(i=0; i<Cities.numCities; i++) {   // each city
        cityID = 'city'+ Cities.cities[i].id;
        for (k in Seed.queue_atkp[cityID]){   // each march
            march = Seed.queue_atkp[cityID][k];
            if (typeof (march) == 'object'){
                for (ii=0; ii<16; ii++){
                    ret.marchUnits[ii] += parseInt (march['unit'+ ii +'Count']);
                    ret.returnUnits[ii] += parseInt (march['unit'+ ii +'Return']);
                }
                for (ii=1; ii<6; ii++){
                    if (march['r'+ ii] && parseInt(march['r'+ ii]) > 0) {
                        ret.resources[ii] += parseInt(march['r'+ ii]);
                    } else {
                        ret.resources[ii] += parseInt(march['resource'+ ii]);
                    }
                }
                if (march['g'] && parseInt(march['g']) > 0) {
                    ret.resources[0] += parseInt(march['g']);
                } else {
                    ret.resources[0] += parseInt(march['gold']);
                }
            }
        }
    }
    return ret;
}
var fortNamesShort = { 53:"" + culang.crossbows + "", 55:"" + culang.trebuchet + "", 60:"" + culang.trap + "", 61:"" + culang.caltr + "", 62:"" + culang.spiked + "", };

function getCityBuilding (cityId, buildingId){
    var b = Seed.buildings['city'+cityId];
    var ret = {count:0, maxLevel:0};
    for (var i in b) {
        var building = b[i];
        if (building[0] == buildingId){
            ++ret.count;
            if (parseInt(building[1]) > ret.maxLevel)
                ret.maxLevel = parseInt(building[1]);
        }
    }
    return ret;
}
function logit (msg){
    var serverID = getServerId();
    var now = new Date();
    //    GM_log (serverID +' @ '+ now.toTimeString().substring (0,8) +'.' + now.getMilliseconds() +': '+  msg);
    GM_log ('\n' + now.toTimeString().substring (0,8) +'.' + now.getMilliseconds() +' @ ' + serverID + ': '+ '\n'+ msg);
}

function readOptions(){var a=getServerId();s=GM_getValue("KsOptions_"+a);if(s!=null){opts=JSON2.parse(s);for(k in opts)Options[k]=opts[k]}}
function saveOptions(){var a=getServerId();GM_setValue("KsOptions_"+a,JSON2.stringify(Options))}
function saveFarmOptions() {var serverID = getServerId();setTimeout(function (){GM_setValue('FarmOptions_' + serverID, JSON2.stringify(FarmOptions)); }, 0);}
function readFarmOptions() {
    var serverID = getServerId();
    s = GM_getValue('FarmOptions_' + serverID);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object') for (kk in opts[k])
                FarmOptions[k][kk] = opts[k][kk];
            else FarmOptions[k] = opts[k];
        }
    }
}
function saveThroneOptions() {var serverID = getServerId();setTimeout(function () { GM_setValue('ThroneOptions_' + serverID, JSON2.stringify(ThroneOptions)); }, 0);}
function readThroneOptions() {
    var serverID = getServerId();
    s = GM_getValue('ThroneOptions_' + serverID);
    if (s != null) {
        opts = JSON2.parse(s);
        for (k in opts) {
            if (matTypeof(opts[k]) == 'object') {
                //if(typeof(ThroneOptions[k])='undefined') continue;//skip unknown (old?) option, DANGEROUS!
                //if(k=='saveXitems'    )continue;
                //if(k=='SalvagePercent')continue;
                //if(k=='SalvageQuality')continue;
                //if(k=='SalvageAdvisor'||k=='SalvageBanner'||k=='SalvageChair'||k=='SalvageTable'||k=='SalvageWindow')continue;
                //if(k=='SalvagePreview')continue;
                //if(k=='Salvage'       )continue;
                if(typeof(ThroneOptions[k])=='undefined') ThroneOptions[k]={};
                for (kk in opts[k])    {
                    if (matTypeof(opts[k][kk]) == 'object') {
                        if(typeof(ThroneOptions[k][kk])=='undefined') ThroneOptions[k][kk]={};
                        for (kkk in opts[k][kk]){
                            ThroneOptions[k][kk][kkk] = opts[k][kk][kkk];
                        }
                    }else ThroneOptions[k][kk] = opts[k][kk];
                }
            }
            else ThroneOptions[k] = opts[k];
        }

        var filter=ThroneOptions.SalvageV2.EffectFilter;
        for (i in unsafeWindow.cm.thronestats.effects) {
            if(typeof(filter[i])=='undefined') filter[i]={IsEnabled:false,IsEnabled2:false,IsEnabled3:false,Value:''};
            if(typeof(filter[i].IsEnabled ) == "undefined" || filter[i].IsEnabled ===null) filter[i].IsEnabled =false;
            if(typeof(filter[i].IsEnabled2) == "undefined" || filter[i].IsEnabled2===null) filter[i].IsEnabled2=false;
            if(typeof(filter[i].IsEnabled3) == "undefined" || filter[i].IsEnabled3===null) filter[i].IsEnabled3=false;
            if(typeof(filter[i].Percent   ) == "undefined" || filter[i].Percent   ===null) filter[i].Percent   ='';
            if(typeof(filter[i].PercentAdvisor) == "undefined") filter[i].PercentAdvisor='';
            if(typeof(filter[i].PercentBanner ) == "undefined") filter[i].PercentBanner ='';
            if(typeof(filter[i].PercentChair  ) == "undefined") filter[i].PercentChair  ='';
            if(typeof(filter[i].PercentTable  ) == "undefined") filter[i].PercentTable  ='';
            if(typeof(filter[i].PercentWindow ) == "undefined") filter[i].PercentWindow ='';
            if(typeof(filter[i].PercentTrophy ) == "undefined") filter[i].PercentTrophy ='';    
            if(typeof(filter[i].PercentCandelabrum ) == "undefined") filter[i].PercentCandelabrum ='';    
        }
    }
}

function saveLangOptions (){setTimeout (function (){GM_setValue ('LangOptions_', JSON2.stringify(LangOptions));}, 0);}
function saveColors (){var serverID = getServerId();GM_setValue('Colors', JSON2.stringify(Colors));}
function readColors (){
    var serverID = getServerId();
    s = GM_getValue ('Colors');
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts)
            Colors[k] = opts[k];
    }
}
function saveUpgradeData (){var serverID = getServerId();setTimeout (function (){GM_setValue ('UpgradeData_'+serverID, JSON2.stringify(upgradeData));}, 0);}
function readUpgradeData (){
    var serverID = getServerId();
    s = GM_getValue ('UpgradeData_'+serverID);
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    upgradeData[k][kk] = opts[k][kk];
            else
                upgradeData[k] = opts[k];
        }
    }
}
function readCombatOptions (){
    var serverID = getServerId();
    s = GM_getValue ('CombatOptions_' + Seed.player['name'] + '_' +serverID);
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    if (matTypeof(opts[k][kk]) == 'object')
                        for (kkk in opts[k][kk])
                            CombatOptions[k][kk][kkk] = opts[k][kk][kkk];
                    else
                        CombatOptions[k][kk] = opts[k][kk];
            else
                CombatOptions[k] = opts[k];
        }
    }
}
function saveCombatOptions (){var serverID = getServerId();setTimeout (function (){GM_setValue ('CombatOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(CombatOptions));}, 0);}
function saveApothecaryOptions (){var serverID = getServerId();setTimeout (function (){GM_setValue ('ApothecaryOptions_' + Seed.player['name'] + '_' +serverID, JSON2.stringify(ApothecaryOptions));}, 0);}
function readApothecaryOptions (){
    var serverID = getServerId();
    s = GM_getValue ('ApothecaryOptions_'+Seed.player['name']+'_'+serverID, '[]');
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    ApothecaryOptions[k][kk] = opts[k][kk];
            else
                ApothecaryOptions[k] = opts[k];
        }
    }
}
function saveTabOptions (){  var serverID = getServerId();  setTimeout (function (){GM_setValue ('TabOptions_'+serverID, JSON2.stringify(TabOptions));}, 0);}
function readTabOptions (){
    var serverID = getServerId();
    s = GM_getValue ('TabOptions_'+serverID);
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    TabOptions[k][kk] = opts[k][kk];
            else
                TabOptions[k] = opts[k];
        }
    }
}
function createButton (label){
    var a=document.createElement('a');
    // a.className='button20';
    a.innerHTML=' '+ label +' ';
    return a;
}
function createBlinkButton (label){
    var a=document.createElement('a');
    a.className='button20';
    a.innerHTML=''+ label +'';
    return a;
}

function AddMainTabLink(text, eventListener, mouseListener) {
    var a = createButton ("<IMG height='36' src='"+IMGbuttonPower+"'  alt='POWER' title='KoC Power - Main Tabs'>");
    a.className='tab';
    a.style.background='none';
    a.id = 'pdxTabs';
    var tabs=ById('main_engagement_tabs');

    if(!tabs) {
        tabs=ById('topnav_msg');
        if (tabs)
            tabs=tabs.parentNode;
    }
    if(tabs) {
        eNew2 = document.createElement('div');
        eNew2.id = 'ksQuick';
        eNew2.className='tabs_engagement';
        eNew2.style.padding='3px';
        eNew2.style.whiteSpace='nowrap';
        eNew2.style.width='745px';
        tabs.parentNode.insertBefore (eNew2, tabs);
        //eNew2.innerHTML="<a id=KsSupportChat style='float:right;margin-right:20px;' title='"+culang.ksSupportChat+"'><img src='"+IMGSupportLogo+"'></a><span style='float:right;padding:5px;font-size:12px;text-shadow: 5px 2px 5px #FGFGFG; font-variant:small-caps; border-radius:18px 0px 18px 0px;  border: 1px inset none;background: url("+IMGksBG+");  -moz-box-shadow: 0px 0px 2px 2px #141516; color:#FFFFFF;'><center><b><a target='_blank' href='"+KsScriptPage+"' title='"+ScriptName+"'>"+ScriptName+"</a>: <a target='_blank' href='"+KsInstallLink+"' title='"+culang.ksInstallLatestNote+"'>"+Version+"</a></b></center></span>";
        eNew2.innerHTML="<a id=KsSupportChat style='float:right;margin-right:20px;' title='"+culang.ksSupportChat+"'></a><span style='float:right;padding:5px;font-size:12px;text-shadow: 5px 2px 5px #FGFGFG; font-variant:small-caps; border-radius:18px 0px 18px 0px;  border: 1px inset none;background: url("+IMGksBG+");  -moz-box-shadow: 0px 0px 2px 2px #141516; color:#FFFFFF;'><center><b><a target='_blank' href='"+KsScriptPage+"' title='"+ScriptName+"'>"+ScriptName+"</a>: <a target='_blank' href='"+KsInstallLink+"' title='"+culang.ksInstallLatestNote+"'>"+Version+"</a></b></center></span>";

        var e = tabs.parentNode;
        var eNew = null;
        for (var i=0; i<e.childNodes.length; i++){
            var ee = e.childNodes[i];

            if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' &&  ee.id!='main_engagement_tabs' &&  ee.id!='ksQuick'){
                eNew = ee;
                break;
            }
        }
        if (eNew == null){
            eNew = document.createElement('div');
            eNew.className='tabs_engagement';
            eNew.style.padding='3px';
            tabs.parentNode.insertBefore (eNew, tabs);
            eNew.id = 'gmTabs';
            eNew.style.whiteSpace='nowrap';
            eNew.style.width='745px';
            eNew.style.height='20px';
            eNew.style.maxHeight='55px';
        }
        if (eNew2.firstChild){
            eNew2.insertBefore (a, eNew2.firstChild);
        }else{
            eNew2.appendChild(a);
        }



        ById("KsSupportChat").addEventListener('click',function() {
            window.open(homePage+"/support/chat");
        }, false);
        a.addEventListener('click',eventListener, false);
        if (mouseListener != null)
            a.addEventListener('mousedown',mouseListener, true);


        if (tabs) {
            GM_xmlhttpRequest({method:"GET",url:""+KsInstallLink+"",onload:function(a){var b=/\/\/\s*@version\s+(.+)\s*\n/i.exec(a.responseText);
                var c=Version;if(b){if(b[1]>c){
                    var eNewMAJ=createBlinkButton ("<IMG height='32' src='"+IMGpdxTeam+"' title='"+culang.updateButtonNote+": "+b[1]+"'>"); 
                    eNewMAJ.className='tab';
                    eNewMAJ.style.background='none';
                    eNewMAJ.id="pdxUpdate";
                    eNewMAJ.title=culang.updateButtonNote;
                    eNew2.insertBefore(eNewMAJ,eNew2.firstChild);
                    eNewMAJ.addEventListener('click',function() {
                        window.open(KsInstallLink);
                    }, false);
                    if (Options.postMultiUpdate) sendChat ("/a (update) - "+culang.updateButtonNote+" "+culang.mainVersion+": "+b[1]+"");

                }}},onerror:function(a){}})


        }


        return a;
    }
    return null;
}
function AddMainTabLink2(text, eventListener, mouseListener) {
        var b = createButton ("<IMG height='36' src='"+IMGbuttonQuick+"'  alt='POWER' title='KoC Power - Quick Tabs'>");
    b.className='tab';
    b.style.background='none';
    b.id = 'pdxTabs2';

    var tabs=ById('main_engagement_tabs');
    if(!tabs) {
        tabs=ById('topnav_msg');
        if (tabs)
            tabs=tabs.parentNode;
    }
    if(tabs) {

        var e = tabs.parentNode;
        var eNew = null;
        for (var i=0; i<e.childNodes.length; i++){
            var ee = e.childNodes[i];

            if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' &&  ee.id!='main_engagement_tabs' &&  ee.id!='ksQuick'){
                eNew = ee;
                break;
            }
        }
        if (eNew == null){
            eNew = document.createElement('div');
            eNew.className='tabs_engagement';
            tabs.parentNode.insertBefore (eNew, tabs);
            eNew.id = 'gmTabs';
            eNew.style.whiteSpace='nowrap';
            eNew.style.width='745px';
        }
        if (eNew2.firstChild){
            eNew2.insertBefore (b, eNew2.firstChild);
        }else{
            eNew2.appendChild(b);
        }

        b.addEventListener('click',eventListener, false);
        if (mouseListener != null)
            b.addEventListener('mousedown',mouseListener, true);
        return b;
    }
    return null;
}

unsafeWindow.PTscout = function (x, y){
    var a=confirm(""+culang.scoutSendconfirm+"");
    if (a) {
        setTimeout (function (){
            ById('mapXCoor').value = x;
            ById('mapYCoor').value = y;
            unsafeWindow.Modal.hideModalAll();
            unsafeWindow.reCenterMapWithCoor();
            unsafeWindow.changeview_map(ById('mod_views_map'));
            unsafeWindow.modal_attack(3,x,y);
            setTimeout (function (){
                var scouter = ById('modal_attack_unit_ipt3');
                scouter.value=1;
                var evt = document.createEvent("KeyboardEvent");
                if(evt.initKeyboardEvent) {
                    evt.initKeyboardEvent("keyup",true,true,null,false,false,false,false,0x10,0);
                } else {
                    evt.initKeyEvent("keyup",true,true,null,false,false,false,false,0x10,0);
                }
                scouter.dispatchEvent(evt);
                unsafeWindow.modal_attack_do();
            }, 500);
        }, 0);
    }
};

function makeButton20 (label){
    var a = document.createElement('a');
    a.className = "button20 ptButton20";
    var s = document.createElement('span');
    s.innerHTML = label;
    a.appendChild (s);
    return a;
}

function strButton20 (label, tags){
    if (tags == null)
        tags = '';
    return ('<TABLE class=ptNoPad><TR><TD><A class="button20 ptButton20" '+ tags +'><SPAN>'+ label +'</span></a></td></tr></table>' );
}

function strButton14 (label, tags){
    if (tags == null)
        tags = '';
    return ('<A class="button14 ptButton20" '+ tags +'><SPAN>'+ label +'</span></a>' );
}

function cityStatusString (cs){
    if (cs==4)
        return 'Vacation';
    if (cs==3)
        return 'Truce';
    if (cs==2)
        return 'Beg Protection';
    return 'Normal';
}

function sendChat (msg){
    var m = ById("mod_comm_input")
    m.value = msg;
    uW.Chat.sendChat();
}
function doDefTrain (cityId, siege, unitId, num, notify){
    var time = unsafeWindow.modal_walls_traintime(unitId, num);
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = cityId;
    params.type = unitId;
    params.quant = num;
    params.items = siege;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/fortify.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function (rslt) {
            if (rslt.ok) {
                unsafeWindow.seed.queue_fort["city" + cityId].push([unitId, num, rslt.initTS, parseInt(rslt.initTS) + time, 0, time, rslt.fortifyId]);
                if (notify != null)
                    setTimeout (function (){notify(null);}, 500);
            } else {
                if (notify != null)
                    setTimeout (function (){notify(rslt.errorMsg);}, 500);
            }
        },
        onFailure: function () {
            if (notify != null)
                notify(rslt.errorMsg);
        },
    });
}
function doTrain (cityId, tut, gam, unitId, num, notify){
    var time = unsafeWindow.modal_barracks_traintime(unitId, num);
    if(tut==36){time=parseInt(time*0.7)}else{if(tut==37){time=parseInt(time*0.5)}else{if(tut==38){time=parseInt(time*0.3)}}}
    var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
    params.cid = cityId;
    params.type = unitId;
    params.quant = num;
    params.items = tut;
    params.gambleId = gam;
    new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/train.php" + unsafeWindow.g_ajaxsuffix, {
        method: "post",
        parameters: params,
        onSuccess: function(rslt) {
            if (rslt.ok) {
                var resourceFactors=[],resourceLost;
                if(gam!=null){
                    time=rslt.timeNeeded;
                }
                for(var i=1;i<5;i++){
                    if(rslt.gamble){
                        resourceFactors.push(rslt.gamble[i.toString()]);
                    }else{
                        resourceFactors.push(1);
                    }
                    resourceLost=parseInt(unsafeWindow.unitcost["unt"+unitId][i])*3600*parseInt(num);resourceLost=resourceLost*resourceFactors[i-1];
                    unsafeWindow.seed.resources["city"+cityId]["rec"+i][0]=parseInt(unsafeWindow.seed.resources["city"+cityId]["rec"+i][0])-resourceLost;
                }
                unsafeWindow.seed.citystats["city"+cityId].gold[0]=parseInt(unsafeWindow.seed.citystats["city"+cityId].gold[0])-parseInt(unsafeWindow.unitcost["unt"+unitId][5])*parseInt(num);
                unsafeWindow.seed.citystats["city"+cityId].pop[0]=parseInt(unsafeWindow.seed.citystats["city"+cityId].pop[0])-parseInt(unsafeWindow.unitcost["unt"+unitId][6])*parseInt(num);
                if (parseInt(unitId) > 12) {
                    unsafeWindow.seed.queue_unt["city"+cityId].push([unitId,num,rslt.initTS,parseInt(rslt.initTS)+time,0,time,null,true]);
                } else {
                    unsafeWindow.seed.queue_unt["city"+cityId].push([unitId,num,rslt.initTS,parseInt(rslt.initTS)+time,0,time,null,false]);
                }

                if (tut!=0) unsafeWindow.seed.items["i"+tut]=Number(unsafeWindow.seed.items["i"+tut])-1;
                // if(rslt.updateSeed) { unsafeWindow.update_seed(rslt.updateSeed) }
                if (notify != null)
                    setTimeout (function (){notify(null);}, 100);
            } else {
                if (notify != null){
                    setTimeout (function (){notify(rslt.errorMsg);}, 100);
                }
            }
        },
        onFailure: function(rslt) {
            if (notify != null)
                notify(rslt.errorMsg);
        }
    });
}

function getAbsoluteOffsets (e){
    ret = {left:0, top:0};
    while (e.offsetParent){
        if (e.style.position == 'absolute')
            break;
        ret.left += e.offsetLeft;
        ret.top += e.offsetTop;
        e = e.offsetParent;
    }
    return ret;
}

function getClientCoords(e){
    if (e==null)
        return {x:null, y:null, width:null, height:null};
    var x=0, y=0;
    ret = {x:0, y:0, width:e.clientWidth, height:e.clientHeight};
    while (e.offsetParent != null){
        ret.x += e.offsetLeft;
        ret.y += e.offsetTop;
        e = e.offsetParent;
    }
    return ret;
}

function htmlTitleLine (msg){
    return '<TABLE width=100% cellspacing=0><TR><TD style="padding:0px" width=50%><HR></td><TD style="padding:0px">[ '+ msg +' ]</td><TD style="padding:0px" width=50%><HR></td></tr></table>';
}

//<editor-fold desc="SPLIT:CPopup.js">
function CPopup (prefix, x, y, width, height, enableDrag, onClose) {
    var pop = WinManager.get(prefix);
    if (pop){
        pop.show (false);
        return pop;
    }
    this.BASE_ZINDEX = 123457;
    this.stmaxh = height;
    this.stmaxw = width;
    this.show = show;
    this.toggleHide = toggleHide;
    this.getTopDiv = getTopDiv;
    this.getMainTopDiv = getMainTopDiv;
    this.getMainDiv = getMainDiv;
    this.getLayer = getLayer;
    this.setLayer = setLayer;
    this.setEnableDrag = setEnableDrag;
    this.getLocation = getLocation;
    this.setLocation = setLocation;
    this.focusMe = focusMe;
    this.isShown = isShown;
    this.unfocusMe = unfocusMe;
    this.centerMe = centerMe;
    this.destroy = destroy;
    this.autoHeight = autoHeight;
    this.autoWidth = autoWidth;
    this.div = document.createElement('div');
    this.prefix = prefix;
    this.onClose = onClose;
    var t = this;
    this.div.className = 'ksCPopup '+ prefix +'_CPopup';
    this.div.id = prefix +'_outer';
    this.div.style.background = "#fff";
    this.div.style.zIndex = this.BASE_ZINDEX;
    this.div.setAttribute("style", "padding:5px; display:none; resize: both; overflow-x:auto; min-width:150px; min-height:50px; border: 1px outset #141516; border-radius:"+Options.popupBorderRadius+"; background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee;    box-shadow: 2px 2px 2px 2px #eee;");

    if (Options.KsTransparence) this.div.style.opacity = '0.9';
    this.div.style.width = width + 'px';
    // this.div.style.height = height + 'px';
    this.div.style.maxHeight = height + 'px';

    this.div.style.position = "absolute";
    this.div.style.top = y +'px';
    this.div.style.left = x + 'px';
    this.div.style.width = width + 'px';
    this.div.style.maxWidth = width + 'px';
    topClass = 'ksCPopupTop '+ prefix +'_CPopupTop';

    if (Options.pdxMenuLeft) {
        var m = '<TABLE cellspacing=0 width=100% height=100%><TR id="'+ prefix +'_bar" class="'+ topClass +'"><TD width=99% valign=bottom  style="background-image: url('+IMGKsTopLogo+'); background-repeat:no-repeat;"><SPAN id="'+ prefix +'_top"></span></td><TD id='+ prefix +'_X align=right valign=middle onmouseover="this.style.cursor=\'pointer\'"><img style="margin-bottom:5px;" width=25px height=25px src="'+IMGcloseButton+'" title="'+culang.mainClose+'"></td></tr><TR><TD height=100% valign=top class="ksCPopMain '+ prefix +'_CPopMain" colspan=2 id="'+ prefix +'_main"></td></tr></table>';
    } else {
        var m = '<TABLE cellspacing=0 width=100% height=100%><TR id="'+ prefix +'_bar" class="'+ topClass +'"><TD width=99% valign=bottom><SPAN id="'+ prefix +'_top"></span></td><TD id='+ prefix +'_X align=right valign=middle onmouseover="this.style.cursor=\'pointer\'" style="padding:5px"><img style="margin-bottom:5px;" width=25px height=25px src="'+IMGcloseButton+'" title="'+culang.mainClose+'"></td></tr><TR><TD height=100% valign=top class="ksCPopMain '+ prefix +'_CPopMain" colspan=2 id="'+ prefix +'_main"></td></tr></table>';
    }
    document.body.appendChild(this.div);
    this.div.innerHTML = m;
    ById(prefix+'_X').addEventListener ('click', e_XClose, false);
    this.dragger = new CWinDrag (ById(prefix+'_bar'), this.div, enableDrag);

    this.div.addEventListener ('mousedown', e_divClicked, false);
    WinManager.add(prefix, this);

    function e_divClicked (){
        t.focusMe();
    }
    function e_XClose (){
        t.show(false);
        if (t.onClose != null)
            t.onClose();
    }
    function autoHeight (onoff){
        if (onoff) {
            t.div.style.height = '';
            t.div.style.maxHeight ='';
        } else{
            t.div.style.height = t.stmaxh;
            t.div.style.maxHeight = t.stmaxh;
        }
    }
    function autoWidth (onoff){
        if (onoff) {
            t.div.style.width = '';
            t.div.style.maxWidth ='';
        } else{
            t.div.style.width = t.stmaxw;
            t.div.style.maxWidth = t.stmaxw;
        }
    }
    function focusMe (){
        t.setLayer(5);
        for (k in unsafeWindow.cpopupWins){
            if (k != t.prefix)
                unsafeWindow.cpopupWins[k].unfocusMe();
        }
    }
    function unfocusMe (){
        t.setLayer(-5);
    }
    function getLocation (){
        return {x: parseInt(this.div.style.left), y: parseInt(this.div.style.top)};
    }
    function setLocation (loc){
        t.div.style.left = loc.x +'px';
        t.div.style.top = loc.y +'px';
    }
    function destroy (){
        document.body.removeChild(t.div);
        WinManager.delete (t.prefix);
    }
    function centerMe (parent){
        if (parent == null){
            var coords = getClientCoords(document.body);
        } else
            var coords = getClientCoords(parent);
        var x = ((coords.width - parseInt(t.div.style.width)) / 2) + coords.x;
        var y = ((coords.height - parseInt(t.div.style.height)) / 2) + coords.y;
        if (x<0)
            x = 0;
        if (y<0)
            y = 0;
        t.div.style.left = x +'px';
        t.div.style.top = y +'px';
    }
    function setEnableDrag (tf){
        t.dragger.setEnable(tf);
    }
    function setLayer(zi){
        t.div.style.zIndex = ''+ (this.BASE_ZINDEX + zi);
    }
    function getLayer(){
        return parseInt(t.div.style.zIndex) - this.BASE_ZINDEX;
    }
    function getTopDiv(){
        return ById(this.prefix+'_top');
    }
    function getMainDiv(){
        return ById(this.prefix+'_main');
    }
    function getMainTopDiv(){
        return ById(this.prefix+'_top');
    }
    function isShown (){
        return t.div.style.display == 'block';
    }
    function show(tf){
        if (tf){
            t.div.style.display = 'block';
            t.focusMe ();
        } else {
            t.div.style.display = 'none';
        }
        return tf;
    }
    function toggleHide(t){
        if (t.div.style.display == 'block') {
            return t.show (false);
        } else {
            return t.show (true);
        }
    }
}
//</editor-fold>
//<editor-fold desc="SPLIT:CWinDrag.js">
function CWinDrag (clickableElement, movingDiv, enabled) {
    var t=this;
    this.setEnable = setEnable;
    this.setBoundRect = setBoundRect;
    this.debug = debug;
    this.dispEvent = dispEvent;
    this.lastX = null;
    this.lastY = null;
    this.enabled = true;
    this.moving = false;
    this.theDiv = movingDiv;
    this.body = document.body;
    this.ce = clickableElement;
    this.moveHandler = new CeventMove(this).handler;
    this.outHandler = new CeventOut(this).handler;
    this.upHandler = new CeventUp(this).handler;
    this.downHandler = new CeventDown(this).handler;
    this.clickableRect = null;
    this.boundRect = null;
    this.bounds = null;
    this.enabled = false;
    if (enabled == null)
        enabled = true;
    this.setEnable (enabled);

    function setBoundRect (b){
        this.boundRect = boundRect;
        this.bounds = null;
    }

    function setEnable (enable){
        if (enable == t.enabled)
            return;
        if (enable){
            clickableElement.addEventListener('mousedown',  t.downHandler, false);
            t.body.addEventListener('mouseup', t.upHandler, false);
        } else {
            clickableElement.removeEventListener('mousedown', t.downHandler, false);
            t.body.removeEventListener('mouseup', t.upHandler, false);
        }
        t.enabled = enable;
    }

    function CeventDown (that){
        this.handler = handler;
        var t = that;
        function handler (me){
            if (t.bounds == null){
                t.clickableRect = getClientCoords(clickableElement);
                t.bodyRect = getClientCoords(document.body);
                if (t.boundRect == null)
                    t.boundRect = t.clickableRect;
                t.bounds = {top:10-t.clickableRect.height, bot:t.bodyRect.height-25, left:40-t.clickableRect.width, right:t.bodyRect.width-25};
            }
            if (me.button==0 && t.enabled){
                t.body.addEventListener('mousemove', t.moveHandler, true);
                t.body.addEventListener('mouseout', t.outHandler, true);
                t.lastX = me.clientX;
                t.lastY = me.clientY;
                t.moving = true;
            }
        }
    }

    function CeventUp  (that){
        this.handler = handler;
        var t = that;
        function handler (me){
            if (me.button==0 && t.moving)
                _doneMoving(t);
        }
    }

    function _doneMoving (t){
        t.body.removeEventListener('mousemove', t.moveHandler, true);
        t.body.removeEventListener('mouseout', t.outHandler, true);
        t.moving = false;
    }

    function CeventOut  (that){
        this.handler = handler;
        var t = that;
        function handler (me){
            if (me.button==0){
                t.moveHandler (me);
            }
        }
    }

    function CeventMove (that){
        this.handler = handler;
        var t = that;
        function handler (me){
            if (t.enabled && !t.wentOut){
                var newTop = parseInt(t.theDiv.style.top) + me.clientY - t.lastY;
                var newLeft = parseInt(t.theDiv.style.left) + me.clientX - t.lastX;
                if (newTop < t.bounds.top){     // if out-of-bounds...
                    newTop = t.bounds.top;
                    _doneMoving(t);
                } else if (newLeft < t.bounds.left){
                    newLeft = t.bounds.left;
                    _doneMoving(t);
                } else if (newLeft > t.bounds.right){
                    newLeft = t.bounds.right;
                    _doneMoving(t);
                } else if (newTop > t.bounds.bot){
                    newTop = t.bounds.bot;
                    _doneMoving(t);
                }
                t.theDiv.style.top = newTop + 'px';
                t.theDiv.style.left = newLeft + 'px';
                t.lastX = me.clientX;
                t.lastY = me.clientY;
            }
        }
    }

    function debug  (msg, e){
        logit ("*************** "+ msg +" ****************");
        logit ('clientWidth, Height: '+ e.clientWidth +','+ e.clientHeight);
        logit ('offsetLeft, Top, Width, Height (parent): '+ e.offsetLeft +','+ e.offsetTop +','+ e.offsetWidth +','+ e.offsetHeight +' ('+ e.offsetParent +')');
        logit ('scrollLeft, Top, Width, Height: '+ e.scrollLeft +','+ e.scrollTop +','+ e.scrollWidth +','+ e.scrollHeight);
    }

    function dispEvent (msg, me){
        logit (msg + ' Button:'+ me.button +' Screen:'+ me.screenX +','+ me.screenY +' client:'+  me.clientX +','+ me.clientY +' rTarget: '+ me.relatedTarget);
    }
}
//</editor-fold>

var WinManager = {
    wins:{},
    didHide:[],

    get:function (prefix) {
        var t = WinManager;
        return t.wins[prefix];
    },

    add:function (prefix, pop) {
        var t = WinManager;
        t.wins[prefix] = pop;
        if (unsafeWindow.cpopupWins == null)
            unsafeWindow.cpopupWins = {};
        unsafeWindow.cpopupWins[prefix] = pop;
    },

    hideAll:function () {
        var t = WinManager;
        t.didHide = [];
        for (k in t.wins) {
            if (t.wins[k].isShown()) {
                t.didHide.push(t.wins[k]);
                t.wins[k].show(false);
            }
        }
    },
    restoreAll:function () {
        var t = WinManager;
        for (var i = 0; i < t.didHide.length; i++)
            t.didHide[i].show(true);
    },

    delete:function (prefix) {
        var t = WinManager;
        delete t.wins[prefix];
        delete unsafeWindow.cpopupWins[prefix];
    }
};

Array.prototype.compare = function (testArr) {
    if (this.length != testArr.length) return false;
    for (var i = 0; i < testArr.length; i++) {
        if (this[i].compare) {
            if (!this[i].compare(testArr[i])) return false;
        }
        if (this[i] !== testArr[i]) return false;
    }
    return true;
};

Array.prototype.contains = function(val) {
    var i = this.length;
    while (i--) {
        if (this[i] == val) {
            return true;
        }
    }
    return false;
}

String.prototype.entityTrans = {  '&agrave;':'\\u00e0', '&eacute;':'\\u00e9', '&':'&amp;', '<':'&lt;',  '>':'&gt;',  '\"':'&quot;', '\'':'&#039', '<':'\\u003c', '/':'\\/', '\\':'\\\\', '\"':'\\\"','{':'&#123;','}':'&#125;'};

String.prototype.htmlEntities = function () {
    var ret = this.toString();
    for (k in this.entityTrans)
        ret = ret.split(k).join(this.entityTrans[k]);
    return ret;
};
String.prototype.htmlSpecialChars = function () {
    var ret = this.toString();
    for (k in this.entityTrans)
        ret = ret.split(k).join(this.entityTrans[k]);
    return ret;
};
String.prototype.htmlSpecialCharsDecode = function () {
    var ret = this.toString();
    for (k in this.entityTrans)
        ret = ret.split(this.entityTrans[k]).join(k);
    return ret;
};
String.prototype.stripTags = function () {
    return this.replace(/<\w+(\s+("[^"]*"|'[^']*'|[^>])+)?>|<\/\w+>/gi, '');
};

String.prototype.capitalize = function () {
    return this.charAt(0).toUpperCase() + this.substring(1).toLowerCase();
};
String.prototype.mreplace = function(obj) {
    var ret = this.toString();
    for (k in obj) {
        var e = new RegExp('{'+k+'}',"g");
        ret = ret.replace(e, obj[k]);
    }
    return ret;
}
function objectName (o){
    var s = o.toString();
    return s.substr(7,s.length-8);
}

function matTypeof (v){
    if (v == undefined)
        return 'undefined';
    if (typeof (v) == 'object'){
        if (!v)
            return 'null';
        else if (v.constructor.toString().indexOf("Array")>=0 && typeof(v.splice)=='function')
            return 'array';
        else return 'object';
    }
    return typeof (v);
}
function matTypeof (v){//TODO replace duplicate
    if (v == undefined)
        return 'undefined';
    if (typeof (v) == 'object'){
        if (!v)
            return 'null';
//    else if (unsafeWindow.Object.prototype.toString.apply(v) === '[object Array]')
        else if (v.constructor.toString().indexOf("Array")>=0 && typeof(v.splice)=='function')
            return 'array';
        else return 'object';
    }
    return typeof (v);
};
        
function addCommasInt(n){
    nStr = parseInt(n) + '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(nStr)) {
        nStr = nStr.replace(rgx, '$1' + THOUSANDS_SEP + '$2');
    }
    return nStr;
}

function addCommas(nStr){
    nStr += '';
    x = nStr.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? DEC_POINT + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + THOUSANDS_SEP + '$2');
    }
    return x1 + x2;
}

function formatDate(Timestamp, FormatString) {
    FormatString = FormatString + "";

    UnixDate = new Date(Timestamp * 1000);
    var out = new Object();

    //Jahr
    out.y = UnixDate.getYear() - 100 + "";
    out.Y = "" + (out.y - 0 + 2000);

    //Monat
    out.n = UnixDate.getMonth() + 1;
    if (out.n > 9) {
        out.m = out.n;
    } else {
        out.m = '0' + out.n;
    }
    out.F = MONTH_NAMES[out.n - 1];
    out.M = MONTH_NAMES[out.n + 11];
    
    //Tag
    out.j = UnixDate.getDate();
    if (out.j > 9) {
        out.d = out.j;
    } else {
        out.d = '0' + out.j;
    }
    if (out.j == 1 || out.j == 21 || out.j == 31) {
        out.S = 'st';
    } else if (out.j == 2 || out.j == 22) {
        out.S = 'nd';
    } else if (out.j == 3 || out.j == 23) {
        out.S = 'rd';
    } else {
        out.S = 'th';
    }
    
    //Wochentag
    out.w = UnixDate.getDay();
    out.D = DAY_NAMES[out.w + 7];
    out.l = DAY_NAMES[out.w];
    
    //Stunden 24h
    out.G = UnixDate.getHours();
    if (out.G > 9) {
        out.H = out.G;
    } else {
        out.H = '0' + out.G;
    }
    
    //Stunden 12h
    if (out.G == 0) {
        out.g = 12;
    } else {
        if (out.G > 12) {
            out.g = out.G - 12;
        } else {
            out.g = out.G;
        }
    }
    if (out.g > 9) {
        out.h = out.g;
    } else {
        out.h = '0' + out.g;
    }
    
    //AM oder PM
    if (out.G > 11) {
        out.a = "pm";
        out.A = "PM";
    } else {
        out.a = "am";
        out.A = "AM";
    }
    
    //Minute
    var m = UnixDate.getMinutes();    
    if (m > 9) {
        out.i = m;
    } else {
        out.i = '0' + m;
    }
    
    //Sekunde
    var s = UnixDate.getSeconds();    
    if (s > 9) {
        out.s = s;
    } else {
        out.s = '0' + s;
    }
    //Formatierten String bauen
    var ret = '';
    var v = 0;
    var G = "";
    var f = "";
    while (v < FormatString.length) {
        G = FormatString.charAt(v);
        f = "";
        while ((FormatString.charAt(v) == G) && (v < FormatString.length)) {
            f += FormatString.charAt(v++);
        }
        if (out[f] != null) {
            ret = ret + out[f];
        } else {
            ret = ret + f;
        }
    }
    return ret;
}

function htmlSelector(a,b,c){m=[];m.push("<SELECT");if(c){m.push(" ");m.push(c)}for(k in a){m.push("><OPTION ");if(k==b)m.push("SELECTED ");m.push('value="');m.push(k);m.push('">');m.push(a[k]);m.push("</option>")}m.push("</select>");return m.join("")}
function unixTime(){ return parseInt (new Date().getTime() / 1000) + unsafeWindow.g_timeoff;}
function timestrShort(a){a=parseInt(a);if(a>86400){var b=[];a/=3600;b.push(parseInt(a/24));b.push("d ");b.push(parseInt(a%24));b.push("h ");return b.join("")}else return timestr(a)}
function timestr(a,b){a=parseInt(a);var c=[];var d=a;if(d<61)return d+"s";if(d>86400){c.push(parseInt(d/86400));c.push("d ");d%=86400}if(d>3600||a>3600){c.push(parseInt(d/3600));c.push("h ");d%=3600}c.push(parseInt(d/60));c.push("m");if(b||a<=3600){c.push(" ");c.push(d%60);c.push("s")}return c.join("")}
function getMyAlliance(){if(Seed.allianceDiplomacies==null||Seed.allianceDiplomacies.allianceName==null)return[0,""+culang.mainNone+""];else return[Seed.allianceDiplomacies.allianceId,Seed.allianceDiplomacies.allianceName]}
function addCommasWhole(a){a+="";x=a.split(".");x1=x[0];x2=x.length>1?"."+x[1]:"";var b=/(\d+)(\d{3})/;while(b.test(x1)){x1=x1.replace(b,"$1"+","+"$2")}return x1}
function CmatSimpleSound (playerUrl, container, attrs, onLoad, flashVars) {
    var self = this;
    this.player = null;
    this.volume = 100;
    this.isLoaded = false;
    this.onSwfLoaded = null;
    var div = document.createElement ('div');
    this.onSwfLoaded = onLoad;
    if (navigator.appName.toLowerCase().indexOf('microsoft')+1) {
        div.innerHTML = '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"><param name="movie" value="'+playerUrl+'"><param name="quality" value="high"></object>';
        this.player = div.getElementsByTagName('object')[0];
    } else {
        div.innerHTML = '<embed src="'+playerUrl+'"  bgcolor="#eeeeee" allowfullscreen=false FlashVars="'+ flashVars +'" quality="high" allowscriptaccess="always" pluginspage="http://www.macromedia.com/go/getflashplayer" type="application/x-shockwave-flash" ></embed>';
        this.player = div.getElementsByTagName('embed')[0].wrappedJSObject;
    }
    if (container)
        container.appendChild (div);
    else
        document.body.appendChild (div);
    for (k in attrs)
        this.player.setAttribute(k, attrs[k]);

    this.setVolume = function (chanNum, vol) {
        if (!self.isLoaded)
            return;
        self.player.jsSetVolume(chanNum, vol);
        volume = vol;
    };

    this.load = function (chanNum, url, bStream, bAutoplay, bUsePolicyFile) {
        self.player.jsLoad(chanNum, url, bStream, bAutoplay, bUsePolicyFile);
    };

    this.play = function (chanNum, position) {
        if (this.isLoaded) {
            if (self.player.jsPlay)  self.player.jsPlay(chanNum, position);
        }
    };

    this.stop = function (chanNum) {
        if (!self.isLoaded)
            return;
        self.player.jsStop(chanNum);
    };

    this.getStatus = function (chanNum) {
        if (this.isLoaded)
            return self.player.jsGetStatus(chanNum);
    };

    this.debugFunc = function (msg) {
    };

    this.swfDebug = function (msg) {
        self.debugFunc('SWF: ' + msg);
    };
    this.swfLoaded = function () {
        self.isLoaded = true;
        self.debugFunc('playerIsReady');
        if (self.onSwfLoaded)
            self.onSwfLoaded();
    };
    this.swfPlayComplete = function (chanNum) {
    };
    this.swfLoadComplete = function (chanNum, isError){
    }
}

function SliderBar (container, width, height, value, classPrefix, margin){
    var self = this;
    this.listener = null;
    if (value==null)
        value = 0;
    if (!margin)
        margin = parseInt(width*.05);
    this.value = value;
    if (width<20) width=20;
    if (height<5) height=5;
    if (classPrefix == null){
        classPrefix = 'slider';
        var noClass = true;
    }
    var sliderHeight = parseInt(height/2);
    var sliderTop = parseInt(height/4);
    this.sliderWidth = width - (margin*2);

    this.div = document.createElement ('div');
    this.div.style.height = height +'px';
    this.div.style.width = width +'px';
    this.div.className = classPrefix +'Cont';
    if (noClass)
        this.div.style.backgroundColor='#ddd';

    this.slider = document.createElement ('div');
    this.slider.setAttribute ('style', 'position:relative;');
    this.slider.style.height = sliderHeight + 'px';
    this.slider.style.top = sliderTop + 'px';
    this.slider.style.width = this.sliderWidth +'px';
    this.slider.style.left = margin +'px';
    this.slider.className = classPrefix +'Bar';
    this.slider.draggable = true;
    if (noClass)
        this.slider.style.backgroundColor='#fff';

    this.sliderL = document.createElement ('div');
    this.sliderL.setAttribute ('style', 'width:100px; height:100%; position:relative; ');
    this.sliderL.className = classPrefix +'Part';
    this.sliderL.draggable = true;
    if (noClass)
        this.sliderL.style.backgroundColor='#0c0';

    this.knob = document.createElement ('div');
    this.knob.setAttribute ('style', 'width:3px; position:relative; left:0px; background-color:#222');
    this.knob.style.height = height +'px';
    this.knob.style.top = (0-sliderTop) +'px';
    this.knob.className = classPrefix +'Knob';
    this.knob.draggable = true;
    this.slider.appendChild(this.sliderL);
    this.sliderL.appendChild (this.knob);
    this.div.appendChild (this.slider);
    container.appendChild (this.div);
    this.div.addEventListener('mousedown',  mouseDown, false);

    this.getValue = function () {
        return self.value;
    };

    this.setValue = function (val) {
        var relX = (val * self.sliderWidth);
        self.sliderL.style.width = relX + 'px';
        self.knob.style.left = relX + 'px';
        self.value = val;
        if (self.listener)
            self.listener(self.value);
    };

    this.setChangeListener = function (listener) {
        self.listener = listener;
    };

    function moveKnob (me){
        var relX = me.clientX - self.divLeft;
        if (relX < 0)
            relX = 0;
        if (relX > self.sliderWidth)
            relX = self.sliderWidth;
        self.knob.style.left = (relX - (self.knob.clientWidth/2) ) +'px';
        self.sliderL.style.width = relX + 'px';
        self.value =  relX / self.sliderWidth;
        if (self.listener)
            self.listener(self.value);
    }
    function doneMoving (){
        self.div.removeEventListener('mousemove', mouseMove, true);
        document.removeEventListener('mouseup', mouseUp, true);
    }
    function mouseUp (me){
        moveKnob (me);
        doneMoving();
    }

    function mouseDown(me){
        var e = self.slider;
        self.divLeft = 0;
        while (e.offsetParent){
            self.divLeft += e.offsetLeft;
            e = e.offsetParent;
        }
        moveKnob (me);
        document.addEventListener('mouseup',  mouseUp, true);
        self.div.addEventListener('mousemove',  mouseMove, true);
    }
    function mouseMove(me){
        moveKnob (me);
    }
}
function AddSubTabLink(text, eventListener, id) {
    var a = createYellowButton (text,'botbutton');
    a.className='tab';
    var tabs=ById('main_engagement_tabs');
    if(!tabs) {
        tabs=ById('topnav_msg');
        if (tabs)
            tabs=tabs.parentNode;
    }
    if (tabs) {
        var e = tabs.parentNode;
        var gmTabs = null;
        for (var i=0; i<e.childNodes.length; i++){
            var ee = e.childNodes[i];
            if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' && ee.id!='main_engagement_tabs' &&  ee.id!='ksQuick'){
                gmTabs = ee;
                break;
            }
        }
        if (gmTabs == null){
            gmTabs = document.createElement('div');
            gmTabs.className='tabs_engagement';
            tabs.parentNode.insertBefore (gmTabs, tabs);
            gmTabs.style.whiteSpace='nowrap';
            gmTabs.style.width='745px';
            gmTabs.lang = 'en_PB';
        }
        gmTabs.appendChild(a);
        a.addEventListener('click',eventListener, false);
        if (id != null)
            a.id = id;
        return a;
    }
    return null;
}
function AddTowerTab(text, eventListener, id) {
    var a = createRedButton (text,'botbutton');
    a.className='tabs_engagement';
    a.style.background='none';
    a.style.cssFloat="none";
    a.style.left="0px";
    a.style.height="50px";
    a.style.zIndex = 9999999;
    a.title="Attention !!! "+uW.g_js_strings.modaltitles.impatks+" !";
    var tabs=ById('main_engagement_tabs');
    if(!tabs) {
        tabs=ById('topnav_msg');
        if (tabs)
            tabs=tabs.parentNode;
    }
    if (tabs) {
        var e = tabs.parentNode;
        var gmTabs = null;
        for (var i=0; i<e.childNodes.length; i++){
            var ee = e.childNodes[i];
            if (ee.tagName && ee.tagName=='DIV' && ee.className=='tabs_engagement' && ee.id!='main_engagement_tabs' &&  ee.id!='ksQuick'){
                gmTabs = ee;
                break;
            }
        }
        if (gmTabs == null){
            gmTabs = document.createElement('div');
            gmTabs.className='tabs_engagement';
            tabs.parentNode.insertBefore (gmTabs, tabs);
            gmTabs.style.whiteSpace='nowrap';
            gmTabs.style.width='745px';
            gmTabs.lang = 'en_PB';
        }
        gmTabs.appendChild(a);
        a.addEventListener('click',eventListener, false);
        if (id != null)
            a.id = id;
        return a;
    }
    return null;
}

function estETA(dist, unit, cityID, typemarche) {
    var ret={ETA:0,etaStr:culang.shortNotAvailable,friendETA:0,friendEtaStr:culang.shortNotAvailable};
    if (dist <= 0) return ret;
    var troop_type = unit;
    var horse=0;
    if(troop_type>6) horse=1;
    var troop_speed=parseInt(unsafeWindow.unitstats["unt"+troop_type][3])*(1+0.1*parseInt(Seed.tech.tch11));
    if (horse){
        troop_speed=troop_speed*(1+0.05*parseInt(Seed.tech.tch12))
    }
    var Speed = troop_speed;


    var throne67=uW.cm.ThroneController.effectBonus(67);
    var throne68,throne69,throne70,throne71,throne72;throne68=throne69=throne70=throne71=throne72=0;
    if(typemarche==4){
        throne68 = uW.cm.ThroneController.effectBonus(68); // attaque
    }else{
        if(typemarche==3){ //eclaireur
            throne72=uW.cm.ThroneController.effectBonus(72)
        }else{
            if(typemarche==2){ //renforce
                throne69=uW.cm.ThroneController.effectBonus(69)
            }else{
                if(typemarche==5){ // reassign
                    throne71=uW.cm.ThroneController.effectBonus(71)
                }else{
                    if(typemarche==1){ // transport
                        throne70=uW.cm.ThroneController.effectBonus(70)}}}}}

    var throneBoost=throne67+throne68+throne69+throne70+throne71+throne72;

    Speed=Speed*(1+(throneBoost*0.01));

    var gi=unsafeWindow.cm.guardianModalModel.getMarchBonus();
    var multiplier=1+(gi*0.01);
    Speed=Speed*multiplier;
    var gSpeed = 0;
    var estSec;
    if (Speed>0) {
        gSpeed = Speed/6000;
        estSec = Math.ceil(parseFloat(dist)/gSpeed);
    }

    var e=1;
    if (ById("Ksitem_55")) {
        var l_elem=ById("Ksitem_55");
        if(l_elem&&l_elem.checked>0){ e=0.75;     }
    }
    if (ById("Ksitem_57")) {
        var l_elem=ById("Ksitem_57");
        if(l_elem&&l_elem.checked){   e=0.5;   }
    }
    ret.ETA = (parseInt((estSec*e+''))+30);
    if(Seed.playerEffects.returnExpire>unsafeWindow.unixtime()){
        ret.ETA=parseInt(ret.ETA*0.5);
    }
    ret.etaStr = timestr (ret.ETA,1);
    if (cityID!=0) {
        var building = getCityBuilding (cityID, 18);
        if (building) {
            fSpeed = Speed * (1 + parseInt(building.maxLevel)/2);
            gSpeed = fSpeed/6000;
            estSec = (dist/gSpeed).toFixed(0);
            ret.friendETA = parseInt((estSec*e+''))+30;
            ret.friendEtaStr = timestr ((ret.friendETA+''),1);
        }
    } else {
        ret.friendETA = ret.ETA;
        ret.friendEtaStr = timestr ((ret.friendETA+''),1);
    }
    return ret;
}

// function updatebotbutton2(a,b){var c=ById(b);if(c)c.innerHTML='<span style="color: #F71F02">'+a.replace("= "+culang.buttonON,butON).replace("= "+culang.buttonOFF,butOFF)+"</span>"}
// function updatebotbutton(a,b){var c=ById(b);if(c)c.innerHTML='<span style="color: #ff6">'+a.replace("= "+culang.buttonON,butON).replace("= "+culang.buttonOFF,butOFF)+"</span>"}
// function createRedButton(a,b){var c=document.createElement("a");c.style.display='none';c.style.background='none';c.id=b;c.innerHTML='<span style="color: #ff6">'+a+"</span>";return c}
// function createRedButton (a){
    // var c=document.createElement('a');
    //c.className='button20';
    // c.innerHTML=' '+ a +' ';
    // return c;
// }
function createRedButton(a,b){
var c=document.createElement("a");
c.style.display='none';
c.id=b;c.innerHTML='<span style="color: #ff6">'+a+"</span>";return c}
// c.className="button20";
function createYellowButton(a,b){
    var c=document.createElement("a");c.className="button20";c.id=b;
    c.innerHTML='<span style="color: #ff6">'+a.replace("= "+culang.buttonON,butON).replace("= "+culang.buttonOFF,butOFF)+'</span>';
    return c
}

/** Creates a recursive object dump
 *
 * @param {object} object the root object to dump.
 * @param {string} name of root object.
 * @return {string} string representation (dump) of object.
 */
function dump(object,rootName) {
    //GM_log("dump "+rootName);
    function dumpInternal(obj, path) {
        //GM_log("dumpInternal "+path);
        if(obj===null) {
            s += "" + path +": {null}" + "\n";
            return;
        } else if(obj===undefined){
            s += "" + path +": {undefined}" + "\n";
            return;
        }
        var valueType = typeof(obj);
        switch (valueType) {
            case "function": return;
            case "object"  : s+= "" + path +": {} -->" /*+ propValue.toString().substr(0,20)*/ + "\n";break;
            case "boolean" : s+= "" + path +": "+ obj.toString() + "\n";return;
            case "number"  : s+= "" + path +": "+ obj.toString() + "\n";return;
            case "string"  : s+= "" + path +": \""+ obj.toString() + "\"\n";return;
            default:s += "" + path +" ("+ valueType +"): "+ obj.toString() + "\n";return;
        }
        
        for (var o in objs) {
            if(o===obj) {
                s+= "{!Recursion stoped!}\n";
                return;
            } else objs.push(obj);
        }

        ++ind;
        for (var propName in obj) dumpInternal(obj[propName], path+"."+propName);
        --ind;
    }
    var objs = [];
    var ind = 0;
    var s = "";
    if(typeof(rootName)=='undefined')rootName="*";
    dumpInternal(object,rootName);
    return s;
};
//<editor-fold desc="SPLIT:Features/DeleteReports.js">
var DeleteReports = {
    trace:false, //set to 'true' to write a trace with logit
    deleting:false,
    deletes1:new Array(),
    deletes0:new Array(),
    timer:null,
    firstReport:null,
    stopAtReport:null, 
    
    init:function () {
        var t = DeleteReports;
        if(t.trace) logit("DeleteReports: init()")
        clearInterval(t.timer);
        if (!t.deleting && (Options.DeleteMsg || Options.DeleteMsgs0 || Options.DeleteMsgs4 || Options.DeleteMsgs5 || Options.DeleteMsgs6 || Options.DeleteMsgs1 || Options.DeleteMsgs2 || Options.DeleteMsgs3)) {
            if (parseIntNan(Options.DeleteTimerMinute) < 2) Options.DeleteTimerMinute = 2;
            t.timer = setInterval(t.startdeletereports, Options.DeleteTimerMinute * 60000);
            if(t.trace) logit("DeleteReports: setInterval "+ Options.DeleteTimerMinute * 60000);        
        }
    },

    startdeletereports:function () {
        var t = DeleteReports;
        if(t.trace) logit("DeleteReports: startdeletereports()")

        if(t.deleting) {
            if(t.trace) logit("DeleteReports: startdeletereports return >> deleting=true")
            return;
        }
        if (!(Options.DeleteMsg || Options.DeleteMsgs0 || Options.DeleteMsgs4 || Options.DeleteMsgs5 || Options.DeleteMsgs6 || Options.DeleteMsgs1 || Options.DeleteMsgs2 || Options.DeleteMsgs3)) {
            if(t.trace) logit("DeleteReports: startdeletereports return >> no Options checked")
            return;
        }
        t.firstReport=null;
        t.deletes1 = new Array();
        t.deletes0 = new Array();
        t.deleting = true;
        t.fetchreport(0, t.checkreports);
    },

    fetchreport:function (pageNo, callback) {
        var t = DeleteReports;
        if(t.trace) logit("DeleteReports: fetchreport(pageNo:"+pageNo+",callback)");
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        if (pageNo > 1)
            params.pageNo = pageNo;
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/listReports.php" + unsafeWindow.g_ajaxsuffix, {
            method:"post",
            parameters:params,
            onSuccess:function (rslt) {
                if(t.trace) logit("DeleteReports: AjaxRequest(listReports.php) Success");
                callback(rslt, pageNo); // >> t.checkreports
            },
            onFailure:function () {
                if(t.trace) logit("DeleteReports: AjaxRequest(listReports.php) Failure");
                callback(); // >> t.checkreports
            },
        });
    },

    checkreports:function (rslt, pageNo) {
        var t = DeleteReports;
        if(t.trace) logit("DeleteReports: checkreports(rslt, pageNo:"+pageNo+")");
        
        var doParseReports = true;
        var doGetNextPage  = true;
        var totalPages     = 0;
        
        if (doParseReports && !rslt.ok) {
            if(t.trace) logit("\nDeleteReports: checkreports <?> !rslt.ok");
            // t.deleting = false; return;
            doParseReports=false;
        }
        if (doParseReports && typeof(rslt.arReports)=='undefined') {
            /* dump of rslt
            rslt: {}
                ok: true
                error_code: 9
                data: {}
            */
            if(false) { // A - stop
                if(t.trace) logit("DeleteReports: checkreports <?> rslt.arReports == undefined"+"\n"+dump(rslt,"rslt")+"\nStop reading reports.");
                t.deleting = false; 
                return;
            }
            if(false) { // B - try again
                if(t.trace) logit("DeleteReports: checkreports <?> rslt.arReports == undefined"+"\n"+dump(rslt,"rslt")+"\nWaiting 1 min and try again");
                setTimeout(function(){t.fetchreport(pageNo, t.checkreports); },5000);            
                return;
            }
            if(true) { // C - skip the current page
                if(t.trace) logit("DeleteReports: checkreports <?> rslt.arReports == undefined"+"\n"+dump(rslt,"rslt")+"\nSkip current page");
                doParseReports=false;
            }
        }
        if (doParseReports && rslt.arReports.length < 1) {
            if(t.trace) logit("DeleteReports: checkreports <?> rslt.arReports.length < 1");
            // t.deleting = false; return;
            doParseReports=false;
        }
        
        if(doParseReports) {
            actionLog("" + culang.mainReports + "", "" + culang.reportDelete + " " + (pageNo + 1) + "/" + rslt.totalPages + " " + culang.reportDelete2 + "");
            var reports = rslt.arReports;
            totalPages = rslt.totalPages;

            for (k in reports) {
                /*
                reports["0r12345678"]: {} -->
                    reportType: "0"
                    reportId: "12345678"
                    reportUnixTime: "1337530325"
                    side0XCoord: "604"
                    side0YCoord: "610"
                    side0TileType: "51"
                    side0TileLevel: "12"
                    side0CityId: "56297"
                    side0PlayerId: "14177235"
                    side0AllianceId: "0"
                    side1XCoord: "602"
                    side1YCoord: "601"
                    side1CityId: "38409"
                    side1PlayerId: "9675639"
                    side1AllianceId: "2288"
                    marchType: "4"
                    marchTypeState: "2"
                    userId: "9675639"
                    eventType: "0"
                    subType: "0"
                    reportStatus: "2"
                    reportDetailId: "0"
                */
                if(pageNo==0) t.firstReport=reports[k].reportId;
                //if(t.stopAtReport!==null && (reports[k].reportId<t.stopAtReport))doGetNextPage=false;
                //GM_log(dump(reports[k],"reports["+k+"]"));
            
                if (Options.DeleteMsg) {
                    if ((reports[k].marchType == 9 || reports[k].marchType == 4) && reports[k].side0PlayerId == 0 && reports[k].side0TileType > 50)
                        t.deletes1.push(k.substr(2));
                    else if (reports[k].marchType == 1 && t.isMyself(reports[k].side1PlayerId))
                        t.deletes1.push(k.substr(2));
                }
                if (Options.DeleteMsgs0) {
                    if (reports[k].marchType == 1 && !t.isMyself(reports[k].side1PlayerId)) {
                        t.deletes0.push(k.substr(2));
                    }
                }
                if (Options.DeleteMsgs1) {
                    if (reports[k].marchType == 4 && (reports[k].side0TileType <= 50) && reports[k].side0PlayerId == 0)
                        t.deletes1.push(k.substr(2));
                }
                if (Options.DeleteMsgs2) {
                    if (reports[k].side0TileType == 54)
                        t.deletes1.push(k.substr(2));
                }
                if (Options.DeleteMsgs3) {
                    if (reports[k].side0TileType == 51 && reports[k].marchType == 2 && t.isMyself(reports[k].side0PlayerId))
                        t.deletes1.push(k.substr(2));
                }
                if (Options.DeleteMsgs4) {
                    if (reports[k].side0TileType == 51 && reports[k].marchType == 3)
                        t.deletes1.push(k.substr(2));
                }
                if (Options.DeleteMsgs5) {
                    if (reports[k].side0TileType == 51 && reports[k].marchType == 4)
                        t.deletes1.push(k.substr(2));
                }
                if (Options.DeleteMsgs6) {
                    for (var i = 0; i < CrestData.length; i++) {
                        x = CrestData[i].X;
                        y = CrestData[i].Y;
                        if (reports[k].side0XCoord == x && reports[k].side0YCoord == y) {
                            t.deletes1.push(k.substr(2));
                        }
                    }
                }
            }
        } else {
            actionLog("" + culang.mainReports + "", "" + "Error reading reports from page " + (pageNo + 1));  //TODO multilang            
        }
        
        if ((pageNo + 1) == totalPages || parseInt(pageNo + 1) >= 10) {
            if (t.deletes1.length > 0 || t.deletes0.length > 0) {
                t.deleteCheckedReports(t.deletes1, t.deletes0);
            } else {
                actionLog("" + culang.mainReports + "", "" + culang.reportAutoDeleteNoNeed + "");
            }
            doGetNextPage=false;
        }
        
        if(doGetNextPage){
            t.fetchreport(pageNo + 1, t.checkreports);
        } else {
            if(t.firstReport!==null) t.stopAtReport=t.firstReport;
            t.deleting = false;
        }
        
    },
    deleteCheckedReports:function (deletes1, deletes0) {
        var t = DeleteReports;
        if(t.trace) logit("DeleteReports: deleteCheckedReports(["+t.deletes1.length+"],["+t.deletes0.length+"])");
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        params.s1rids = deletes1.join(",");
        params.s0rids = deletes0.join(",");
        params.cityrids = '';
        new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/deleteCheckedReports.php" + unsafeWindow.g_ajaxsuffix, {
            method:"post",
            parameters:params,
            onSuccess:function (rslt) {
                if(t.trace) logit("DeleteReports: AjaxRequest(deleteCheckedReports.php) Success ok:"+rslt.ok==true);
                if (rslt.ok) {
                    Seed.newReportCount = parseInt(Seed.newReportCount) - parseInt(deletes1.length) - parseInt(deletes0.length);
                    actionLog("" + culang.mainReports + "", "" + culang.reportAutoDelete + " " + (parseInt(deletes1.length) + parseInt(deletes0.length)) + "");
                } else {
                    actionLog("" + culang.mainReports + "", "" + culang.mainError + ": " + rslt.msg);
                }
                t.deleting = false;
            },
            onFailure:function () {
                if(t.trace) logit("DeleteReports: AjaxRequest(deleteCheckedReports.php) Failure");
                actionLog("" + culang.mainReports + "", "" + culang.mainError + ": " + rslt.msg);
                t.deleting = false;
            },
        });
    },
    isMyself:function (userID) {
        var t = DeleteReports;
        if (!Seed.players["u" + userID])
            return false;
        if (Seed.players["u" + userID].n == Seed.player.name)
            return true;
        else
            return false;
        return false;
    },
};
//</editor-fold>
//<editor-fold desc="SPLIT:tabManager.js">
var tabManager = {
    tabList : {},
    currentTab : null,
    init : function (mainDiv){
        var t = tabManager;
        var sorter = [];
        for (k in Tabs){
            if (!Tabs[k].tabDisabled){
                t.tabList[k] = {};
                t.tabList[k].name = k;
                t.tabList[k].obj = Tabs[k];
                if (Tabs[k].tabLabel != null)
                    t.tabList[k].label = Tabs[k].tabLabel;
                else
                    t.tabList[k].label = k;
                if (Tabs[k].tabOrder != null)
                    sorter.push([Tabs[k].tabOrder, t.tabList[k]]);
                else
                    sorter.push([1000, t.tabList[k]]);
                t.tabList[k].div = document.createElement('div');
            }
        }

        sorter.sort (function (a,b){return a[0]-b[0]});

        if (Options.pdxMenuLeft) {
            var m = '<div class=pdxMenu style="position:fixed; margin-left:-120px;margin-top:-36px;padding:2px; border: 1px outset #141516; border-radius:'+Options.popupBorderRadius+'; background-color:#FFFFFF; -moz-box-shadow: 2px 2px 2px 2px #eee; -webkit-box-shadow: 2px 2px 2px 2px #eee; box-shadow: 2px 2px 2px 2px #eee;"><TABLE cellspacing=0 cellpadding=0 class=multiMainTabs>';
            for (var i=0; i<sorter.length; i++){
                m += '<TR><TD class=spacer></td><TD class=ksTabNotSelLeft id=pbtc'+ sorter[i][1].name +'><A><SPAN class="multiTab">'+ sorter[i][1].label +'</span></a></td></tr>';
            }
            m+='</table></div>';
        } else {
            var m = '<TABLE cellspacing=0 cellpadding=0 class=multiMainTabs><TR>';
            for (var i=0; i<sorter.length; i++){
                m += '<TD class=spacer></td><TD class=ksTabNotSel id=pbtc'+ sorter[i][1].name +'><A><SPAN class="multiTab">'+ sorter[i][1].label +'</span></a></td>';
                if (i==8) m+='</tr><tr>';
                if (i==17) m+='</tr><tr>';
            }
            m+='</tr></table></div>';
        }

        mainPop.getMainTopDiv().innerHTML = m;

        for (k in t.tabList) {
            if (t.tabList[k].name == Options.currentTab)
                t.currentTab =t.tabList[k] ;
            ById('pbtc'+ k).addEventListener('click', this.e_clickedTab, false);
            var div = t.tabList[k].div;
            div.style.display = 'none';
            div.style.height = '100%';
            mainDiv.appendChild(div);
            try {
                t.tabList[k].obj.init(div);
            } catch (e){

            }
        }

        if (t.currentTab == null)
            t.currentTab = sorter[0][1];
        t.setTabStyle (document.getElementById ('pbtc'+ t.currentTab.name), true);
        t.currentTab.div.style.display = 'block';
    },

    hideTab : function (){
        var t = tabManager;
        t.currentTab.obj.hide();
    },

    showTab : function (){
        var t = tabManager;
        t.currentTab.obj.show();
    },

    setTabStyle : function (e, selected){
        if (selected){
            if (Options.pdxMenuLeft) {  e.className = 'ksTabSelLeft'; } else { e.className = 'ksTabSel'; }
        } else {
            if (Options.pdxMenuLeft) {  e.className = 'ksTabNotSelLeft'; } else { e.className = 'ksTabNotSel'; }
        }
    },

    e_clickedTab : function (e){
        var t = tabManager;
        newTab = t.tabList[e.target.parentNode.parentNode.id.substring(4)];
        if (t.currentTab.name != newTab.name){
            t.setTabStyle (document.getElementById ('pbtc'+ t.currentTab.name), false);
            t.setTabStyle (document.getElementById ('pbtc'+ newTab.name), true);
            t.currentTab.obj.hide ();
            t.currentTab.div.style.display = 'none';
            t.currentTab = newTab;
            newTab.div.style.display = 'block';
            Options.currentTab = newTab.name;
        }
        newTab.obj.show();
    },
}
//</editor-fold>
/*************** March Tab **********/
  Tabs.Attaque = {
   cont : null,
   displayTimer : null,
   tabLabel : 'Rally Point',
   state : null,
   curTabBut : null,
   curTabName : null,
   BOAttackTimer: null,
   sourceCity : {},
   destinationCity : {},
   rows : [],
   iused : new Array(),
   init : function (div){
     var t = Tabs.Attaque;
     t.cont = div;
     t.state = null;
     clearTimeout (t.displayTimer);
   },
    getContent : function (){
      var t = Tabs.Attaque;
      return t.cont;
    },
    hide : function (){
      var t = Tabs.Attaque;
      t.state = null;
      clearTimeout (t.displayTimer);
    },
    show : function (){
      var t = Tabs.Attaque;
      var rownum = 0;
      var ModelCity = {};
   
      if (t.state == null) {
           m = "<DIV class=ptstat><b>MARCH TOOL</b></div>";
           m +="<div id='statpourRAA'></div>"; 
           m += "<TABLE width=600 class=ptTab border=0 align=center>\
             <tr><td><INPUT type=checkbox id=ptmarch_autoknight "+(Options.marchautoknight?'CHECKED':'')+" /> Auto select knight</td></tr>\
             <tr><td colspan=4 align=center><input type=button id=REEaction value='Scout'>&nbsp;<input type=button id=RAAaction value='Attack'>&nbsp<input type=button id=RARaction value='Reassign'>&nbsp;<input type=button id=RENaction value='Reinforce'>&nbsp;<input type=button id=RENBaction value='Reinforce + Max Food'></td></tr><tr align=center valign=top><td width=130><b><u>Source</b></u><br><span id=RAAsrcRptspeedcity></span></td>\
             <td><b><u>Destination</b></u><br>X:<input type=text id=RAAtypetrpx size=3>&nbsp;Y:<input type=text id=RAAtypetrpy size=3><br><a href='javascript:void(0);' id='BOchargelistelieux'>Fetch Members</a> : <select id='listeFavori'></select></td>\
             <td><b><u>Distance</u></b><br><span id='BOEstimationD'>&nbsp;</span><td><b><u>Closest City</u></b><br><span id=BOVilleProche></span>\
             </tr><tr align=center valign=top>\
             <td colspan=4 align=left><table border=0 bordercolor=black cellspacing=0 cellpadding=0 width=100% style='text-align:center'><tr><td rowspan=14><div id=RAAstatsource></div></td><td colspan=2><a href='javascript:void(0)' id=BO_RAZ_Units title='Clear' >Units Selected</a></td><td>Attack Time</td><td>Reinforce Time</td></tr>";
  //            for (r=1; r<13; r++){
              for (r=1; r<14; r++){
              m += '<tr><td align=right><img height=20 title="'+unsafeWindow.unitcost['unt'+r][0]+'" src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td><td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="RAAnbunit'+r+'" type=text size=7 value="0" ></td><td><span id="BOEstimationTT'+r+'">&nbsp;</span></td><td><span id="BOEstimationTZ'+r+'">&nbsp;</span></td></tr>';
            }
            var itemlist=[55,57,931,932];
      var BOitems="";
      for(var i=0;i<itemlist.length;i++){
           BOitems += "<img src='http://kabam1-a.akamaihd.net/kingdomsofcamelot/fb/e2/src/img/items/30/"+itemlist[i]+".jpg' /><input type=checkbox id='BOitem_"+itemlist[i]+"'><span id='BOitemSpan_"+itemlist[i]+"'>" + unsafeWindow.ksoItems[itemlist[i]].count + "</span>&nbsp;";
          }
          m += "</table></td></tr>\
                <tr><td colspan=4>Knight : <SELECT id='RAApiKnight' type=list></select> <br>"+BOitems+"</td></tr></table>\
                <DIV class=ptstat>Saved Unit Configuration :</div><TABLE><tr><td colspan=2><select id=BO_AT_Fav></select><input type=button value='Reset' id=BO_AT_Fav_Sup><input type=button value='Reset All' id=BO_AT_Fav_RESET></td><td colspan=2>New : <input type=type id=BO_AT_Fav_Nom size=10 maxlength=12>&nbsp;<input type=button value='Save Troops' id=BO_AT_Fav_ajou>\
                <tr><td colspan=4><div id=ptRAAStatus style='overflow-y:auto; max-height:50px; height: 50px;'></div></td></tr></table>\
                <DIV class=ptstat>Auto Attack - Work in Progress</div><table></tr><tr><td><input type=button id='BOActiveAttack' value='ACTIVER : OFF' ></td><td colspan=3><span id='BOCompAttack'></span></tr>\
                <tr><td><b>Heure arriv&eacute;e :</b> <input type=text size=7 id='BOHorloge' value='" + Options.AttackHorloge + "'></td><td><input type=button value='Enregistrer' id='BOSaveAttack'></td><td><input type=button value='Editer l\'attaque' id='BOEditAttack' disabled></td></tr>\
                <tr><td colspan=4><span id='BOAttackProg'></span></td></tr></table>";
          t.cont.innerHTML = m;
          t.statpourRAA = ById ('statpourRAA');
          //Gestion des favoris
          t.Favoris = ById ('BO_AT_Fav');
      function metajourfavori() {
             t.Favoris.innerHTML="<option value=''>...</option>";
             var lisf = Options.AttackFav;
             for (var m in lisf) {
               var lis = lisf[m];
                t.Favoris.innerHTML+="<option value='"+m+"'>"+lis[0]+"</option>";
                   }
      }
   
      ById("ptmarch_autoknight").addEventListener('click', function(){
          Options.marchautoknight = this.checked;
          saveOptions();
          t.show();
      },false);
         ById("BO_AT_Fav_RESET").addEventListener ('click', function() {
           Options.AttackFav={};
           saveOptions();
           metajourfavori();
         }, false);
         ById("BO_AT_Fav_Sup").addEventListener ('click', function() {
         numfav=ById("BO_AT_Fav").value;
         if (numfav!="") {
          Options.AttackFav[numfav]={};
          delete Options.AttackFav[numfav];
          //Options.AttackFav=unset(Options.AttackFav, numfav);
          saveOptions();
          metajourfavori();
         }
         }, false);
         ById("BO_RAZ_Units").addEventListener ('click', function() {
  //      for (r=1; r<13; r++) ById("RAAnbunit"+r).value=0;
        for (r=1; r<14; r++) ById("RAAnbunit"+r).value=0;
       }, false);
         ById("BO_AT_Fav_ajou").addEventListener ('click', function() {
          if (ById("BO_AT_Fav_Nom").value=="") {
           alert("Please fill in a name!");
           return;
          }
          var a =ById("BO_AT_Fav_Nom").value;
          Options.AttackFav[a]={};
          var lisf = Options.AttackFav[a];
          lisf[0]=ById("BO_AT_Fav_Nom").value;
  //        for (r=1; r<13; r++) lisf[r]=ById("RAAnbunit"+r).value;
          for (r=1; r<14; r++) lisf[r]=ById("RAAnbunit"+r).value;
          ById("BO_AT_Fav_Nom").value="";
          saveOptions();
      metajourfavori();
         }, false);
         ById("BO_AT_Fav").addEventListener ('change', function() {
           numfav=ById("BO_AT_Fav").value;
           if (numfav=="") {
  //          for (r=1; r<13; r++) ById("RAAnbunit"+r).value=0;
            for (r=1; r<14; r++) ById("RAAnbunit"+r).value=0;
           }else {
            var lisf = Options.AttackFav[numfav];
            for (var m in lisf) {
             if(m>0)
          if (ById("RAAnbunit"+m)) ById("RAAnbunit"+m).value=lisf[m];
        }
           }
         }, false);
         // Fin gestion des favoris
         ById("BOitem_55").addEventListener ('click', function() {
          ById("BOitem_57").checked=false;
          t.estimerRes();
         }, false);
         ById("BOitem_57").addEventListener ('click', function() {
                ById("BOitem_55").checked=false;
                t.estimerRes();
         }, false);
          t.statutRAA = ById ('ptRAAStatus');
          t.destinationCityx = ById ('RAAtypetrpx');
          t.destinationCityy = ById ('RAAtypetrpy');
          t.destinationCityx.value = Options.Xrenfort;
          t.destinationCityy.value = Options.Yrenfort;
          if (ById ('maparea_map').style.display!="none") {
           t.destinationCityx.value = ById ('mapXCoor').value;
           t.destinationCityy.value = ById ('mapYCoor').value;
          }
          t.listeFavoris = ById ('listeFavori');
          t.listeFavoris.addEventListener ('change', t.SelectFavoris, false);
          t.chargelistelieux = ById ('BOchargelistelieux');
          t.chargelistelieux.addEventListener ('click', t.chercherFavoris, false);
          t.actionREN = ById ('RENaction');
          t.actionRENB = ById ('RENBaction');
          t.actionREE = ById ('REEaction');
          t.actionRAA = ById ('RAAaction');
          t.actionRAR = ById ('RARaction');
   
        t.actionREN.addEventListener ('click', function () { t.clickATTAQUEDo(2,0); }, false);
          t.actionRAA.addEventListener ('click',  function () { t.clickATTAQUEDo(4,0); }, false);
          t.actionRAR.addEventListener ('click',  function () { t.clickATTAQUEDo(5,0); }, false);
          t.actionRENB.addEventListener ('click',  function () { t.clickATTAQUEDo(2,1); }, false);
          t.actionREE.addEventListener ('click',  function () { t.clickATTAQUEDo(3,0); }, false);
          t.destinationCityx.addEventListener ('change', function () { t.estimerRes(); }, false);
          t.destinationCityy.addEventListener ('change', function () { t.estimerRes(); }, false); 
          var dcp0 = new CdispCityPicker ('ptRAA0', ById('RAAsrcRptspeedcity'), false, t.clickRAACitySourceSelect, Cities.byID[unsafeWindow.currentcityid].idx);
          t.estimerRes();
          t.BOAttackProg = ById ('BOAttackProg');
          t.BOHorloge = ById ('BOHorloge');
          t.BOSaveAttack = ById ('BOSaveAttack');
          t.BOEditAttack = ById ('BOEditAttack');
          t.BOCompAttack = ById ('BOCompAttack');
          t.BOActiveAttack  = ById ('BOActiveAttack');
          t.BOActiveAttack.addEventListener ('click', t.AutoattackOnOff, false);
          
          t.BOSaveAttack.addEventListener ('click', function () {
          
            var itemlist=[55,57,931,932];
        for(var i=0;i<itemlist.length;i++){
              ById('BOitemSpan_'+itemlist[i]).checked=false;
            }
          
           t.enregistreAttack();
          
          }, false);
          if (Options.AttackCibleX!=0 && Options.AttackCibleY!=0) {
           t.BOEditAttack.disabled=false;
          }
          t.BOEditAttack.addEventListener ('click', function () {
            t.destinationCityx.value = Options.AttackCibleX;
            t.destinationCityy.value = Options.AttackCibleY;
            ById("RAApiKnight").value=Options.AttackKnight;
            nHtml.Click(ById("ptRAA0_"+Cities.byID[Options.AttackFromCity].idx));
  //          for (r=1; r<13; r++) {
            for (r=1; r<14; r++) {
            ById("RAAnbunit"+r).value=Options.AttackUnits[r-1];
            }
          }, false);
          
          metajourfavori();
          if (Options.AttackOnOff) {
            t.BOActiveAttack.value='ACTIVER : ON';
            t.activeAttack();
          }
          t.clickRAACitySourceSelect(t.sourceCity);
          var closestNum = t.getclosestcity();
          t.dcp1 = new CdispCityPicker ('ptmarch_citydest', ById('BOVilleProche'), false, t.estimerRes, null).bindToXYboxes(ById("RAAtypetrpx"),ById("RAAtypetrpy"));
         }
   
      },
      getclosestcity : function (){
       var t = Tabs.Attaque;
       var x1 = parseInt(t.sourceCity.x);
       var x2 = parseInt(t.destinationCityx.value);
       var y1 = parseInt(t.sourceCity.y);
       var y2 = parseInt(t.destinationCityy.value);
       var dist = distance (x1, y1, x2, y2);
       var closestDist=999999;
       var closestLoc=null;
       var closestNum=1;
       for (var c=0; c<Cities.numCities; c++){
          var city = Cities.cities[c];
          var dist=distance(city.x,city.y,x2,y2);
          if(dist<closestDist) {
           closestDist=dist;
           closestLoc=city.x +','+ city.y;
           closestNum=c;
          }
       }
       return closestNum;
      },
      AutoattackOnOff:function() {
       // click click sur le bouton Activer le compte ÃƒÂƒÃ‚ÂƒÃƒÂ‚Ã‚ÂƒÃƒÂƒÃ‚Â‚ÃƒÂ‚Ã‚ÂƒÃƒÂƒÃ‚ÂƒÃƒÂ‚Ã‚Â‚ÃƒÂƒÃ‚Â‚ÃƒÂ‚Ã‚ÂƒÃƒÂƒÃ‚ÂƒÃƒÂ‚Ã‚ÂƒÃƒÂƒÃ‚Â‚ÃƒÂ‚Ã‚Â‚ÃƒÂƒÃ‚ÂƒÃƒÂ‚Ã‚Â‚ÃƒÂƒÃ‚Â‚ÃƒÂ‚Ã‚ÂƒÃƒÂƒÃ‚ÂƒÃƒÂ‚Ã‚ÂƒÃƒÂƒÃ‚Â‚ÃƒÂ‚Ã‚ÂƒÃƒÂƒÃ‚ÂƒÃƒÂ‚Ã‚Â‚ÃƒÂƒÃ‚Â‚ÃƒÂ‚Ã‚Â†ÃƒÂƒÃ‚ÂƒÃƒÂ‚Ã‚ÂƒÃƒÂƒÃ‚Â‚ÃƒÂ‚Ã‚Â‚ÃƒÂƒÃ‚ÂƒÃƒÂ‚Ã‚Â‚ÃƒÂƒÃ‚Â‚ÃƒÂ‚Ã‚Â’  rebour !
       var t = Tabs.Attaque;
       t.BOCompAttack.innerHTML='';
       clearTimeout (t.BOAttackTimer);
       if (t.BOActiveAttack.value=='ACTIVER : OFF') {
          t.BOActiveAttack.value='ACTIVER : ON';
               Options.AttackOnOff = true;
               saveOptions();
               t.activeAttack();
               
              } else {
               Options.AttackOnOff = false;
               saveOptions();
               t.BOActiveAttack.value='ACTIVER : OFF';
      }
      },
      activeAttack:function() {
       var t = Tabs.Attaque;
       clearTimeout (t.BOAttackTimer);
       if (Options.AttackGoHorloge) {
         var depart=new Date()
         depart.setTime(Options.AttackGoHorloge);
         var now = unixTime()*1000;
         if (now >= Options.AttackGoHorloge) {
      t.BOCompAttack.innerHTML='<center><font color=red>LANCEMENT ATTAQUE EFFECTUE</font></center>';
      t.destinationCityx.value = Options.AttackCibleX;
      t.destinationCityy.value = Options.AttackCibleY;
      ById("RAApiKnight").value=Options.AttackKnight;
      nHtml.Click(ById("ptRAA0_"+Cities.byID[Options.AttackFromCity].idx));
  //    for (r=1; r<13; r++) {
      for (r=1; r<14; r++) {
         ById("RAAnbunit"+r).value=Options.AttackUnits[r-1];
            }
        t.clickATTAQUEDo(4,0);
        clearTimeout (t.BOAttackTimer);
        Options.AttackGoHorloge=null;
        saveOptions();
       }
       if (now > depart.getTime()) {
           t.BOCompAttack.innerHTML='<center><font color=red>IMPOSSIBLE</font></center>';
           clearTimeout (t.BOAttackTimer);
              Options.AttackGoHorloge=null;
           saveOptions();
           return false;
       }
         
       t.BOAttackTimer=setTimeout(function(){
          var depart=new Date();
      depart.setTime(Options.AttackGoHorloge);
          var now = unixTime()*1000;
          var tempsrestant = depart.getTime() - now;
          t.BOCompAttack.innerHTML='<center><font color=red><b>ATTAQUE DANS '+timestr(tempsrestant/1000)+'</b></font></center>';
          t.activeAttack();
        },1000);
       }
      
      },
      enregistreAttack : function() {
       var t = Tabs.Attaque;
       if (t.BOHorloge.value.match("^[0-9]{2}:[0-9]{2}:[0-9]{2}$")) {
         var horloge = t.BOHorloge.value;
         Options.AttackHorloge = horloge;
         
         var ndate=new Date();
         ndate.setHours(horloge.substr(0,2));
         ndate.setMinutes(horloge.substr(3,2));
         ndate.setSeconds(0);
         var atunits=new Array();
  //       for (r=1; r<13; r++) {
         for (r=1; r<14; r++) {
            atunits.push(parseInt(ById("RAAnbunit"+r).value));
         }
         Options.AttackUnits = atunits;
         Options.AttackFromCity = t.sourceCity.id;
         Options.AttackKnight = ById("RAApiKnight").value;
         Options.AttackCibleX = t.destinationCityx.value;
         Options.AttackCibleY = t.destinationCityy.value;
         
         var x1 = parseInt(t.sourceCity.x);
         var x2 = parseInt(t.destinationCityx.value);
         var y1 = parseInt(t.sourceCity.y);
         var y2 = parseInt(t.destinationCityy.value);
         var dist = distance (x1, y1, x2, y2);
         var tempplusgrand=0;
  //       for (r=1; r<13; r++){
         for (r=1; r<14; r++){
           if (parseInt(ById("RAAnbunit"+r).value)>0) {
                 var m = estETA(dist, r, t.sourceCity.id);
                 if (tempplusgrand<m.ETA) tempplusgrand=m.ETA;
           }
         }
         var departtime=ndate.getTime() - (tempplusgrand*1000);
         var depart=new Date()
         depart.setTime(departtime);
         
         var now = unixTime()*1000;
         if (now > depart.getTime()) {
          t.BOAttackProg.innerHTML = "Depart impossible !";
          return false;
         }
         Options.AttackGoHorloge =  depart.getTime();
         saveOptions ();
         t.BOAttackProg.innerHTML = "Attaque sur " + Options.AttackCibleX + ","+ Options.AttackCibleY +" enregistr&eacute;e";
         t.BOEditAttack.disabled=false;
       } else {
        t.BOAttackProg.innerHTML = "Mauvais format de l'horloge.";
       }
      
      },
      clickATTAQUEDo: function(typemarche, bouffe) {
        var t = Tabs.Attaque;
        var totalunit=0;
        if (typemarche==3 && ById("RAAnbunit3").value==0) ById("RAAnbunit3").value=1;
  //      for (r=1; r<13; r++){
        for (r=1; r<14; r++){
           if (typemarche==3 && r!=3) {
            ById("RAAnbunit"+r).value=0;
           }
            if (parseInt(ById("RAAnbunit"+r).value) > parseInt(ById("RAAdestunit"+r).value)) {
              ById("RAAnbunit"+r).style.backgroundColor="red";
              return false;
            }
            totalunit=totalunit+parseInt(ById("RAAnbunit"+r).value);
            ById("RAAnbunit"+r).style.backgroundColor="";
        }
        var errMsg = "";
        if (isNaN (t.destinationCityx.value) ||t.destinationCityx.value<0 || t.destinationCityx.value>749)
              errMsg = "X coordinates must be between 0 and 749<BR>";
        if (isNaN (t.destinationCityy.value) || t.destinationCityy.value<0 || t.destinationCityy.value>749)
         errMsg += "Y coordinates must be between 0 and 749<br>";
        
        if (ById("RAApiKnight").value==0 && typemarche==4) {
         errMsg += "No knight selected!<BR>";
        }
        
        if (errMsg != "") {
             t.statutRAA.innerHTML = "<FONT COLOR=#550000>"+ errMsg +"</font>";
             return;
        }
        
        var x=t.destinationCityx.value;
        var y=t.destinationCityy.value;
        // On sauvegardes les coordonnes en cas de F5
        t.SaveCoordsOptions(x,y);
        
        
        // Les objets pour l'attaque !
        var e=1;
        var eTR = 1;
        var f=unsafeWindow.unixtime();
        if(Seed.playerEffects.aurasExpire){
        if(Seed.playerEffects.aurasExpire>f){e=1.15}}
        if(Seed.playerEffects.auras2Expire){if(Seed.playerEffects.auras2Expire>f){e=1.3}}
   
       var l_elem=ById("BOitem_931");
       if(l_elem&&l_elem.checked&&parseInt(Seed.items["i931"])>0){
         e+=0.25;
        
       }
       var l_elem=ById("BOitem_932");
       if(l_elem&&l_elem.checked&&parseInt(Seed.items["i932"])>0){
         e+=0.5;
       }
       var trmarchsizebuff = 0;
       var trmarchsizebuff = equippedthronestats(66);
       if(trmarchsizebuff > 0)
          eTR=(trmarchsizebuff/100)+1;
  //        e+=(trmarchsizebuff/100);
       if(trmarchsizebuff > 150)
          eTR=2.5;
        var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
        
        if (totalunit==0) {
           t.statutRAA.innerHTML = '<FONT COLOR=#550000>You have no available units!</font>';
             return;
        }
        var niveauPointRall=parseInt(getCityBuilding (t.sourceCity.id, 12).maxLevel); // 12=Point de ralliement
  //
  // Add Ascended city march size bonus
          var ascendrallyfactor = 1.0;
              var isPrestige = Seed.cityData.city[t.sourceCity.id].isPrestigeCity;
          if (isPrestige) {
              if (Seed.cityData.city[t.sourceCity.id].prestigeInfo.prestigeLevel == 1) ascendrallyfactor = 1.55;
              if (Seed.cityData.city[t.sourceCity.id].prestigeInfo.prestigeLevel == 2) ascendrallyfactor = 1.60;
              if (Seed.cityData.city[t.sourceCity.id].prestigeInfo.prestigeLevel == 3) ascendrallyfactor = 1.65;
          }
   
  //"prestigeInfo":{"prestigeType":"1","prestigeLevel":"1","prestigeBuffExpire":1349051413,"blessings":[11]}
  //
           var maxtroupe=parseInt(niveauPointRall*10000*eTR*e * ascendrallyfactor);
           if (niveauPointRall==11) maxtroupe=parseInt(150000*eTR*e * ascendrallyfactor);
           if (niveauPointRall==12) maxtroupe=parseInt(200000*eTR*e * ascendrallyfactor);
        if (totalunit>maxtroupe) {
         t.statutRAA.innerHTML = '<FONT COLOR=#550000>You can only send '+maxtroupe+' units.</font>';
         return;
        }
        var iused=new Array();
        var itemlist=[55,57,931,932];
        for(var i=0;i<itemlist.length;i++){
        
         var l_elem=ById("BOitem_"+itemlist[i]);
         if(l_elem&&l_elem.checked&&parseInt(Seed.items["i"+itemlist[i]])>0){
          iused.push(itemlist[i]); 
         }
        }
        var res=0;
        if (bouffe==1) {
  //       for (var i=1;i<13;i++) {
         for (var i=1;i<14;i++) {
          res += parseInt(unsafeWindow.unitstats['unt'+i][5] * ById("RAAnbunit"+i).value * (1 + (0.10 * Seed.tech.tch10)));
         }
         }
        params.items=iused.join(",");
           params.cid= t.sourceCity.id;
           params.type = typemarche; // 5 = REASSIGNER - 4 = ATTAQUE - 2 = RENFORCER
           params.xcoord = x;
           params.ycoord = y;
          params.kid= ById("RAApiKnight").value;
       params.r1 = res;
       params.r2 = 0;
       params.r3 = 0;
       params.r4 = 0;
       params.gold = 0;
       params.u1 = 0;
         params.u2 = 0;
         params.u3 = 0;
         params.u4 = 0;
         params.u5 = 0;
         params.u6 = 0;
         params.u7 = 0;
         params.u8 = 0;
         params.u9 = 0;
         params.u10 = 0;
         params.u11 = 0;
        params.u12 = 0;
        params.u13 = 0;
   
   
           if (typemarche!=3) {
          if (ById("RAAnbunit1").value>0) params.u1 = ById("RAAnbunit1").value;
      if (ById("RAAnbunit2").value>0) params.u2 = ById("RAAnbunit2").value;
      if (ById("RAAnbunit3").value>0) params.u3 = ById("RAAnbunit3").value;
      if (ById("RAAnbunit4").value>0) params.u4 = ById("RAAnbunit4").value;
      if (ById("RAAnbunit5").value>0) params.u5 = ById("RAAnbunit5").value;
      if (ById("RAAnbunit6").value>0) params.u6 = ById("RAAnbunit6").value;
      if (ById("RAAnbunit7").value>0) params.u7 = ById("RAAnbunit7").value;
      if (ById("RAAnbunit8").value>0) params.u8 = ById("RAAnbunit8").value;
      if (ById("RAAnbunit9").value>0) params.u9 = ById("RAAnbunit9").value;
      if (ById("RAAnbunit10").value>0) params.u10 = ById("RAAnbunit10").value;
      if (ById("RAAnbunit11").value>0) params.u11 = ById("RAAnbunit11").value;
      if (ById("RAAnbunit12").value>0) params.u12 = ById("RAAnbunit12").value;
      if (ById("RAAnbunit13").value>0) params.u13 = ById("RAAnbunit13").value;
      
      }else {
       params.u3 = ById("RAAnbunit3").value;
       ById("RAAnbunit3").value=0;
      }
        t.actionRAA.disabled=true;
          t.actionREN.disabled=true;
          t.actionREE.disabled=true;
      t.statutRAA.innerHTML = "<i><b>Sending march....</b></i>";
      new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/march.php" + unsafeWindow.g_ajaxsuffix, {
                    method: "post",
                    parameters: params,
                    loading: true,
                    onSuccess: function (transport) {
                        var t = Tabs.Attaque;
                        var rslt = transport;
                        if (rslt.ok) {
                 var timediff = parseInt(rslt.eta) - parseInt(rslt.initTS);
                         var ut = unsafeWindow.unixtime();
                         var unitsarr=[0,0,0,0,0,0,0,0,0,0,0,0,0];
                         for(i = 0; i <= unitsarr.length; i++){
                             if(params["u"+i]){
                            unitsarr[i] = params["u"+i];
                            }
                         }
                         var resources=new Array();
                         resources[0] = params.gold;
                         for(i=1; i<=4; i++){
                            resources[i] = params["r"+i];
                         }
                         var currentcityid =  t.sourceCity.id;
                         unsafeWindow.attach_addoutgoingmarch(rslt.marchId, rslt.marchUnixTime, ut + timediff, params.xcoord, params.ycoord, unitsarr, params.type, params.kid, resources, rslt.tileId, rslt.tileType, rslt.tileLevel, currentcityid, true);
                         unsafeWindow.update_seed(rslt.updateSeed)
                         if(rslt.updateSeed){unsafeWindow.update_seed(rslt.updateSeed)};
                         
                         for(var i=0;i<iused.length;i++){
                          Seed.items["i"+iused[i]]=parseInt(Seed.items["i"+iused[i]])-1;unsafeWindow.ksoItems[iused[i]].subtract();
                         }
                          var typeattaque = "";
                          switch (typemarche){
                              case 2:
                                  typeattaque="Reinforce successful";
                                  break;
                              case 3:
                                  typeattaque="Scout successful";
                                  break;
                              case 4:
                                  typeattaque="Attack successful";
                                  break;
                              case 5:
                                  typeattaque="Reassign successful";
                                  break;
                              default:
                                  typeattaque="March successful";
                          }
                       t.statutRAA.innerHTML = "<center><font size='3px'><b>"+typeattaque+"</b></font></center>";
                       t.clickRAACitySourceSelect(t.sourceCity);
                        } else {
                           t.statutRAA.innerHTML ="<font color=red size='3px'><b>Error sending march!<b></font>";
                           if (rslt.msg) {
                             t.statutRAA.innerHTML +="<br><font color=black size='2px'>" + rslt.msg +"</font>";
                           }else{
                             t.statutRAA.innerHTML +="<br>Waiting for 2 seconds!</font>";
                             //setTimeout(function() { t.clickATTAQUEDo(); }, 2000);
                           }
                       }
                       t.actionRAA.disabled=false;
                         t.actionREN.disabled=false;
                         t.actionREE.disabled=false;
                    },
                        onFailure: function () {
                          var t = Tabs.Attaque;
                          t.statutRAA.innerHTML ="<font color=red size='3px'><b>Error communicating with server!<b></font>";
                          t.actionRAA.disabled=false;
                        t.actionREN.disabled=false;
                        t.actionREE.disabled=false;
                        }
                });
              
    
      },
    
      estimerRes: function() {
       var t = Tabs.Attaque;
       // CAlcul de ETA = Estimation du temps de marches
       var x1 = parseInt(t.sourceCity.x);
       var x2 = parseInt(t.destinationCityx.value);
       var y1 = parseInt(t.sourceCity.y);
       var y2 = parseInt(t.destinationCityy.value);
       var dist = distance (x1, y1, x2, y2);
       ById("BOEstimationD").innerHTML = '<b>' + dist + '</b>&nbsp;<a href="javascript:void(0)" onclick="cm.utils.CoordinateLinkController.onClick(event)" class="coordinateLink">('+ t.destinationCityx.value +','+ t.destinationCityy.value +')</a>';
  //     for (r=1; r<13; r++){
       for (r=1; r<14; r++){
          var m = estETA(dist, r, t.sourceCity.id);
          ById("BOEstimationTT"+r).innerHTML = "<b>" + m.etaStr + "</b>";
          ById("BOEstimationTZ"+r).innerHTML = "<b>" + m.friendEtaStr + "</b>";
       }
      },
      SelectFavoris:function() {
        var t = Tabs.Attaque;
        if (t.listeFavoris.value!='') {
         var valeur=t.listeFavoris.value;
         var x=valeur.substr(0, valeur.lastIndexOf(','));
         var y=valeur.substr(valeur.lastIndexOf(',')+1, valeur.length);
         t.destinationCityx.value = x;
         t.destinationCityy.value = y;
        }
        t.estimerRes();
       },
        chercherFavoris: function() {
        var t = Tabs.Attaque;
        var myA = getMyAlliance ();
        if (myA[0]!=0) {
           var params = unsafeWindow.Object.clone(unsafeWindow.g_ajaxparams);
           params.perPage = 100;
           params.allianceId = myA[0];
               new MyAjaxRequest(unsafeWindow.g_ajaxpath + "ajax/getUserLeaderboard.php" + unsafeWindow.g_ajaxsuffix, {
                 method: "post",
                 parameters: params,
                 onSuccess: function (rslt) {
                   // on vide la liste
                   //t.listeFavoris.innerHTML=null;
                   if (rslt.ok){
                    var z=0;
                    var m="";
                    for (var i=0; i<rslt.results.length; i++){
                        p = rslt.results[i];
                   if (p.userId != 0){
                    for (var c=0; c<p.cities.length; c++){
                      if (Seed.player.name!=p.displayName) {
                       m += "<option value='" + p.cities[c].xCoord + ","+ p.cities[c].yCoord+"'>" + p.displayName + " - City " + (c+1) + " - " + p.cities[c].xCoord + "," + p.cities[c].yCoord+"</option>";
                      }
                    }  //fin for cities       
                   }   //fin if user
                           } //fin for resultat
                   t.listeFavoris.innerHTML="<option value=''>Selection...</option>"+m;
                   }// fin
                 },
                 onFailure: function (rslt) {
                   t.listeFavoris.innerHTML="<option>Error getting info</option>";
                 },
             });
               
        } else {
          // Si pas d'alliance !
          t.listeFavoris.innerHTML="<option>Pas d'alliance !</option>";
        }
           
    },
     SaveCoordsOptions: function(x,y) {
         Options.Xrenfort = x;
         Options.Yrenfort = y;
         saveOptions ();
    },
     
    clickRAACitySourceSelect : function (city){
       var t = Tabs.Attaque;
      
       if (t.sourceCity!=city) {
        t.sourceCity = city;
       }
       var m="";
       m="<table cellspacing=0 cellpadding=0 width=80%><tr><td colspan=2>Units Available</td></tr>";
       var cityID = 'city'+ t.sourceCity.id;
  //     for (r=1; r<13; r++){
       for (r=1; r<14; r++){
         m += '<tr><td align=right><img title="'+unsafeWindow.unitcost['unt'+r][0]+'" height=20 src=http://cdn1.kingdomsofcamelot.com/fb/e2/src/img/units/unit_'+r+'_30_s34.jpg></td>\
               <td align=left><input style="border:1px solid black;height:16px;font-size:11px;" id="RAAdestunit'+r+'" type=text size=7 readonly value="'+parseInt(Seed.units[cityID]['unt'+r])+'">&nbsp;\
               <input type=button value="--->" id="RAApdestunit'+r+'"  style="border:1px solid black;height:16px;font-size:11px;"></td></tr>';
   
       }
       m += "</table>";
       ById("RAAstatsource").innerHTML = m;
          var knt = new Array();
          for (k in Seed.knights['city' + t.sourceCity.id]){
                         if (Seed.knights['city' + t.sourceCity.id][k]["knightStatus"] == 1 && Seed.leaders['city' + t.sourceCity.id]["resourcefulnessKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["politicsKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["combatKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"] && Seed.leaders['city' + t.sourceCity.id]["intelligenceKnightId"] != Seed.knights['city' + t.sourceCity.id][k]["knightId"]){
                             knt.push ({
                                 Name:   Seed.knights['city' + t.sourceCity.id][k]["knightName"],
                                 Combat:    Seed.knights['city' + t.sourceCity.id][k]["combat"],
                                 ID:    Seed.knights['city' + t.sourceCity.id][k]["knightId"],
                             });
                         }
                 }
                 knt = knt.sort(function sort(a,b) {a = parseInt(a['Combat']);b = parseInt(b['Combat']);return a == b ? 0 : (a > b ? -1 : 1);});
                 ById('RAApiKnight').options.length=0;
                 var o = document.createElement("option");
                  o.text = "--Select a Knight--"
                  o.value = 0;
                 ById("RAApiKnight").options.add(o);
                 for (k in knt){
                          if (knt[k]["Name"] !=undefined){
                              var o = document.createElement("option");
                              o.text = (knt[k]["Name"] + ' (' + knt[k]["Combat"] +')')
                              o.value = knt[k]["ID"];
                              ById("RAApiKnight").options.add(o);
                          }
           }
       
        if (ById('RAApiKnight').options.length>0) {
            if(Options.marchautoknight)
              ById('RAApiKnight').selectedIndex=1;
        }
        
        var itemlist=[55,57,931,932];
        for(var i=0;i<itemlist.length;i++){
          ById('BOitemSpan_'+itemlist[i]).innerHTML = unsafeWindow.ksoItems[itemlist[i]].count;
        }
  //     for (r=1; r<13; r++){
       for (r=1; r<14; r++){
         ById("RAApdestunit"+r).addEventListener ('click', function() {
           var nomcha=this.id.replace("RAApdest","RAAdest");
           var nomcha2=this.id.replace("RAApdestunit","RAAnbunit");
           ById(nomcha2).value=0;
           var e=1;
       var eTR = 1;
  //         var trmarchsizebuff = 0;
       var trmarchsizebuff = equippedthronestats(66);
       if(trmarchsizebuff > 0)
          eTR=(trmarchsizebuff/100)+1;
  //        e+=(trmarchsizebuff/100);
       if(trmarchsizebuff > 150)
          eTR=2.5;
   
           var f=unsafeWindow.unixtime();
           if(Seed.playerEffects.aurasExpire){if(Seed.playerEffects.aurasExpire>f){e=1.15}}
       if(Seed.playerEffects.auras2Expire){if(Seed.playerEffects.auras2Expire>f){e=1.3}}
   
           var l_elem=ById("BOitem_931");
       if(l_elem&&l_elem.checked&&parseInt(Seed.items["i931"])>0){            e+=0.25;     }
       var l_elem=ById("BOitem_932");
       if(l_elem&&l_elem.checked&&parseInt(Seed.items["i932"])>0){            e+=0.5;     }
   
           var niveauPointRall=parseInt(getCityBuilding (t.sourceCity.id, 12).maxLevel); // 12=Point de ralliement
  //         var maxtroupe=parseInt(niveauPointRall*10000*e);
  //        if (niveauPointRall==11) maxtroupe=parseInt(150000*e);
  //         if (niveauPointRall==12) maxtroupe=parseInt(200000*e);
  //
  // Add Ascended city march size bonus
          var ascendrallyfactor = 1.0;
              var isPrestige = Seed.cityData.city[t.sourceCity.id].isPrestigeCity;
          if (isPrestige) {
              if (Seed.cityData.city[t.sourceCity.id].prestigeInfo.prestigeLevel == 1) ascendrallyfactor = 1.55;
              if (Seed.cityData.city[t.sourceCity.id].prestigeInfo.prestigeLevel == 2) ascendrallyfactor = 1.60;
              if (Seed.cityData.city[t.sourceCity.id].prestigeInfo.prestigeLevel == 3) ascendrallyfactor = 1.65;
          }
   
  //"prestigeInfo":{"prestigeType":"1","prestigeLevel":"1","prestigeBuffExpire":1349051413,"blessings":[11]}
  //
           var maxtroupe=parseInt(niveauPointRall*10000*eTR*e * ascendrallyfactor);
           if (niveauPointRall==11) maxtroupe=parseInt(150000*eTR*e * ascendrallyfactor);
           if (niveauPointRall==12) maxtroupe=parseInt(200000*eTR*e * ascendrallyfactor);
           var nbunitto=0;
  //         for (r=1; r<13; r++) {
           for (r=1; r<14; r++) {
             nbunitto+=parseInt(ById("RAAnbunit"+r).value);
       }
           var libre = parseInt(maxtroupe - nbunitto);
           if (ById(nomcha).value>=libre) {
             ById(nomcha2).value = libre;
           }  else {
             ById(nomcha2).value= ById(nomcha).value;
           }
          }, false);
       }
       if (t.sourceCity!=city) {
  //           for (r=1; r<13; r++){
             for (r=1; r<14; r++){
              ById("RAAnbunit"+r).value="0";
             }
       } else {
            
  //          for (r=1; r<13; r++){
            for (r=1; r<14; r++){
                if (ById("RAAnbunit"+r).value=="") ById("RAAnbunit"+r).value="0";
                if (ById("RAAdestunit"+r).value=="") ById("RAAdestunit"+r).value="0";
                  if (parseInt(ById("RAAnbunit"+r).value)>parseInt(ById("RAAdestunit"+r).value)) {
                   ById("RAAnbunit"+r).value="0";
                  }
             }
       }
       t.estimerRes();
       var closestNum = t.getclosestcity();
       //if(t.dcp1)
          //t.dcp1.selectBut(closestNum);
     },
   
   
  }
   
   
  function equippedthronestats (stat_id){
      var active_slot = Seed.throne.activeSlot;
  //    var equip_items = Seed.throne.slotEquip[1];
      var equip_items = Seed.throne.slotEquip[active_slot];
      var total = 0;
      for(var k = 0; k<equip_items.length; k++){
          var item_id = equip_items[k];
          var item = uW.kocThroneItems[item_id];
          logit(inspect(item,3,1));
          for(var i = 1; i<=item.quality; i++){
  // don't try to look for sixth line if unique quality item
              if (i < 6 ){
              var id = item["effects"]["slot"+i]["id"];
              if(id == stat_id){
                  var tier = parseInt(item["effects"]["slot"+i]["tier"]);
                  var level = item["level"];
                  var p = uW.cm.thronestats.tiers[id][tier];
                  var Percent = p.base + ((level * level + level) * p.growth * 0.5);
                  total += Percent;
              }
              }
          }
      }
      return total;
  }
   
   
  function estETA(dist, unit, cityID) {
      var ret={ETA:0,etaStr:'N/D',friendETA:0,friendEtaStr:'N/D'};
      if (dist <= 0) return ret;
      var troop_type = unit;
      var horse=0;
  //    if(troop_type>6) horse=1;
      if(troop_type>6 && troop_type<13) horse=1;
      var troop_speed=parseInt(unsafeWindow.unitstats["unt"+troop_type][3])*(1+0.1*parseInt(Seed.tech.tch11));
      if (horse){
          troop_speed=troop_speed*(1+0.05*parseInt(Seed.tech.tch12))
      }
      var Speed = troop_speed;
      var gi=unsafeWindow.cm.guardianModalModel.getMarchBonus();
      var multiplier=1+(gi*0.01);
      Speed=Speed*multiplier;
      var gSpeed = 0;
      var estSec;
      if (Speed>0) {
        gSpeed = Speed/6000;
        estSec = Math.ceil(parseFloat(dist)/gSpeed);
      }
      var e=1;
      if (ById("BOitem_55")) {
        var l_elem=ById("BOitem_55");
        if(l_elem&&l_elem.checked>0){ e=0.75;     }
      }
      if (ById("BOitem_57")) {
        var l_elem=ById("BOitem_57");
        if(l_elem&&l_elem.checked){   e=0.5;   }
      }
      ret.ETA = (parseInt((estSec*e+''))+30);
      if(Seed.playerEffects.returnExpire>unsafeWindow.unixtime()){
        ret.ETA=parseInt(ret.ETA*0.5);
      }
      ret.etaStr = timestr (ret.ETA,1);
      var building = getCityBuilding (cityID, 18);
      if (building) {
        fSpeed = Speed * (1 + parseInt(building.maxLevel)/2);
        gSpeed = fSpeed/6000;
        estSec = (dist/gSpeed).toFixed(0);
        ret.friendETA = parseInt((estSec*e+''))+30;
        ret.friendEtaStr = timestr ((ret.friendETA+''),1);
      }
          var isPrestige = Seed.cityData.city[cityID].isPrestigeCity;
      if (isPrestige) {
        fSpeed = Speed * (1 + 5.5);
        gSpeed = fSpeed/6000;
        estSec = (dist/gSpeed).toFixed(0);
        ret.friendETA = parseInt((estSec*e+''))+30;
        ret.friendEtaStr = timestr ((ret.friendETA+''),1);
      }
      return ret;
  }
/*********************************** News TAB ***********************************/
Tabs.News = {
    tabOrder: 301,
  tabDisabled : false,
  tabLabel : 'Ally msg',
  myDiv : null,
  
    init : function (div){
        var t = Tabs.News;
        t.myDiv = div;
    div.innerHTML = '<DIV class=pbStat>Important Info!</div><br>';
        GM_xmlhttpRequest({
            method: 'GET',
            url: 'http://alliance-message-board.googlecode.com/svn/trunk/NewsFeed.txt',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            onload: function (news) {
                if(news.status != 200) {
                    div.innerHTML += '<center><div style="background-color:#DEDEDE; width:600px; height:200px; text-align:left; overflow-y:auto;"><b>Unable to fetch news <br>Error: '+news.status+'</b></div></center>';
                    return;
                }
                var m = '<center>';
                m += '<div style="background-color:#DEDEDE; width:600px; height:200px; text-align:left; overflow-y:auto;">';
                m += '<div id=newsdate></div>'
                m += '<b>'+news.responseText.replace(/\n/g,"<br>")+'</b>';
                m += '</div></center>';
                m += '<div><font color = red>&nbsp&nbsp&nbsp&nbspIntended to only be used for updates and moral.  <br>&nbsp&nbsp&nbsp&nbspex: kabam adds back off wait time, and then asks the community why they think the game is lagging?  Answer they generated fake lag.</div>';
                div.innerHTML += m;
                var first = Number(news.responseHeaders.indexOf("Last-Modified"))+15;
                var last = news.responseHeaders.indexOf("\n",first);
                var lastmodified = news.responseHeaders.slice(first,last);
                if (Options.BreakingNews != lastmodified) {
                    Options.BreakingNews=lastmodified;
                    Options.BreakingNewsV = false;
                    saveOptions();
                }
                if(Options.BreakingNewsV == false)
                setTimeout(t.notify,10000);
                document.getElementById('newsdate').innerHTML = '<p style="text-align: right;">'+Options.BreakingNews+'</p>';
            },
        });
    },
  hide : function (){
    var t = Tabs.News;
  },

  show : function (){
    var t = Tabs.News;
    Options.BreakingNewsV = true;
    saveOptions();
  },
  notify : function() {
    var t = Tabs.News;
    var elem = document.getElementById("pbtcNews");
elem.setAttribute("style","background: -moz-linear-gradient(center top , #ff0000, #b10000) repeat scroll 0 0 transparent;");
  },

}
Tabs.Scripter = {
    tabOrder: 99000,
    tabDisabled : !Options.ScripterTab,
    tabLabel : 'Scripter',
    myDiv : null,
    
    init : function (div) {
        var t = Tabs.Scripter
        t.myDiv = div;
        var m = '<DIV class=pbStat>Scripter</div><br>';
        m += '<center><INPUT id=SCode type=text size=70 maxlength=9999 value="" \></center>'
        div.innerHTML = m;
        
        document.getElementById('SCode').addEventListener ('keypress', function (e){
        if(e.which == 13)
            eval(this.value);
        }, false);
    },
  hide : function (){
    var t = Tabs.Scripter;
  },

  show : function (){
    var t = Tabs.Scripter;
  },  
}

/*********************************** Q&A TAB ***********************************/
Tabs.QA = {
    tabOrder: 302,
  tabDisabled : false,
  tabLabel : 'Q&A',
  myDiv : null,
  
    init : function (div){
        var t = Tabs.QA;
        t.myDiv = div;
    div.innerHTML = '<DIV class=pbStat>Questions And Answers</div><br>';
        GM_xmlhttpRequest({
            method: 'GET',
            url: 'http://alliance-q-and-a-board.googlecode.com/svn/trunk/Q&A.txt',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8',
            },
            onload: function (news) {
                if(news.status != 200) {
                    div.innerHTML += '<center><div style="background-color:#DEDEDE; width:600px; height:200px; text-align:left; overflow-y:auto;"><b>Unable to fetch news <br>Error: '+news.status+'</b></div></center>';
                    return;
                }
                var m = '<center>';
                m += '<div style="background-color:#DEDEDE; width:600px; height:200px; text-align:left; overflow-y:auto;">';
                m += '<div id=newsdate></div>'
                m += '<b>'+news.responseText.replace(/\n/g,"<br>")+'</b>';
                m += '</div></center>';
                m += '<div><font color = red>&nbsp&nbsp&nbsp&nbspIntended for q&a support.  <br>&nbsp&nbsp&nbsp&nbspex: Question what is the best troop to defend with if being hit by cats and range?  Answer Defend with ponies and either CS or defense.</div>';
                div.innerHTML += m;
                var first = Number(news.responseHeaders.indexOf("Last-Modified"))+15;
                var last = news.responseHeaders.indexOf("\n",first);
                var lastmodified = news.responseHeaders.slice(first,last);
                if (Options.BreakingNews != lastmodified) {
                    Options.BreakingNews=lastmodified;
                    Options.BreakingNewsV = false;
                    saveOptions();
                }
                if(Options.BreakingNewsV == false)
                setTimeout(t.notify,10000);
                document.getElementById('newsdate').innerHTML = '<p style="text-align: right;">'+Options.BreakingNews+'</p>';
            },
        });
    },
  hide : function (){
    var t = Tabs.QA;
  },

  show : function (){
    var t = Tabs.QA;
    Options.BreakingNewsV = true;
    saveOptions();
  },
  notify : function() {
    var t = Tabs.QA;
    var elem = document.getElementById("pbtcNews");
elem.setAttribute("style","background: -moz-linear-gradient(center top , #ff0000, #b10000) repeat scroll 0 0 transparent;");
  },

}
Tabs.Scripter = {
    tabOrder: 99000,
    tabDisabled : !Options.ScripterTab,
    tabLabel : 'Scripter',
    myDiv : null,
    
    init : function (div) {
        var t = Tabs.Scripter
        t.myDiv = div;
        var m = '<DIV class=pbStat>Scripter</div><br>';
        m += '<center><INPUT id=SCode type=text size=70 maxlength=9999 value="" \></center>'
        div.innerHTML = m;
        
        document.getElementById('SCode').addEventListener ('keypress', function (e){
        if(e.which == 13)
            eval(this.value);
        }, false);
    },
  hide : function (){
    var t = Tabs.Scripter;
  },

  show : function (){
    var t = Tabs.Scripter;
  },  
}

pdxStartup ();
/********************************************************************************
*                    KOC POWER - KSX BUTTLER                                     *
********************************************************************************/
if (Options.enableButtler) {eval(GM_getResourceText("PLUGIN_BUTTLER")); } else {}

function readLangOptions (){
    s = GM_getValue ('LangOptions_');
    if (s != null){
        opts = JSON2.parse (s);
        for (k in opts){
            if (matTypeof(opts[k]) == 'object')
                for (kk in opts[k])
                    LangOptions[k][kk] = opts[k][kk];
            else
                LangOptions[k] = opts[k];
        }
    }
};
function getThroneItemName(itemId){
    // Selten table von Courage +2
    var levels=["Simple","Common","Uncommon","Rare","Epic","Wondrous"];
    var item=unsafeWindow.kocThroneItems[itemId];

    var name= /*item.name + " / " +*/ levels[1*item.quality]+ " " + item.type + " of " + unsafeWindow.cm.thronestats.effects[item.effects.slot5.id][4] + " +"+item.level;
    return name;
}

/**********************************************************************************
 KOC POWER - END
 greetz fly out to jontey, Nico De Belder, Nessaja and BeWorld...
 this Script was done by koc.god-like.org
 /**********************************************************************************/
 
 
/************ DEBUG WIN *************/

var debugWin = {
  popDebug : null,
  dbDefaultNot : '',
  dbSelect : {},

  doit : function (){
    var t = debugWin;   

    function syncBoxes (){
      var div = document.getElementById('dbpoplist');
      for (var i=0; i<div.childNodes.length; i++){
        if (div.childNodes[i].type && div.childNodes[i].type=='checkbox'){
          var name=div.childNodes[i].name.substr(6);
          div.childNodes[i].checked = t.dbSelect[name];
        }
      }
    }
    function clickedAll (){
      for (var k in t.dbSelect)
        t.dbSelect[k] = true;
      syncBoxes();
    }
    function clickedNone (){
      for (var k in t.dbSelect)
        t.dbSelect[k] = false;
      syncBoxes();
    }
    function clickedDefaults (){
      for (k in t.dbSelect)
        t.dbSelect[k] = false;
      var not = t.dbDefaultNot.split(',');
      for (var i=0; i<not.length; i++)
        t.dbSelect[not[i]] = false;
      syncBoxes();
    }
    function clickedShow (){
      var now = new Date();
      var myseed = unsafeWindow.Object.clone (Seed);
      var div = document.getElementById('dbpoplist');
      for (var i=0; i<div.childNodes.length; i++){
        if (div.childNodes[i].type && div.childNodes[i].type=='checkbox'){
          var name=div.childNodes[i].name.substr(6);
          if (!div.childNodes[i].checked)
            delete myseed[name];
        }
      }
      WinLog.write ("seed @ "+ unixTime()  +" ("+ now +")\n\n"+ inspect (myseed, 8, 1));
      myseed=null;
    }
    
    function clickedShowScripts (){
      var scripts = document.getElementsByTagName('script');
      for (var i=0; i<scripts.length; i++){
        if (scripts[i].src!=null && scripts[i].src!='')
          WinLog.write ('<A style="color:black; text-decoration:underline;" TARGET=_tab HREF="'+ scripts[i].src +'">'+ scripts[i].src +'</a>');
      }
    }
    
    if (t.popDebug == null){ 
      t.popDebug = new CPopup ('db', 0, 0, 600,500, true);
      t.popDebug.getTopDiv().innerHTML = 'DEBUG';
      t.popDebug.getMainDiv().innerHTML = '<DIV><INPUT type=submit id=dbsuball value=ALL> &nbsp; <INPUT type=submit id=dbsubnone value=NONE> &nbsp; \
        <INPUT type=submit id=dbdefaults value=DEFAULTS> &nbsp; <INPUT type=submit id=dbsubdo value=SHOW> &nbsp; <INPUT type=submit id=dbsubscripts value=SCRIPTS></div>\
        <DIV id=dbpoplist style="max-height:400px; height:400px; overflow-y:auto"></div>';
      var div = document.getElementById('dbpoplist');
      for (var k in Seed)
        t.dbSelect[k] = false;
      var not = t.dbDefaultNot.split(',');
      for (var i=0; i<not.length; i++)
        t.dbSelect[not[i]] = false;
      var m = [];
      for (k in t.dbSelect){
        m.push ('<INPUT type=checkbox ');
        m.push ('name="dbpop_');
        m.push (k);
        m.push ('"> &nbsp; ');
        m.push (k);
        m.push ('<BR>');
      }
      div.innerHTML = m.join ('');
      document.getElementById('dbsuball').addEventListener('click', clickedAll, false);
      document.getElementById('dbsubnone').addEventListener('click', clickedNone, false);
      document.getElementById('dbdefaults').addEventListener('click', clickedDefaults, false);
      document.getElementById('dbsubdo').addEventListener('click', clickedShow, false);
      document.getElementById('dbsubscripts').addEventListener('click', clickedShowScripts, false);
      syncBoxes();
    }
    t.popDebug.show (true);
  },
}

var WINLOG_MAX_ENTRIES = 1000;     // TODO
var WinLog = {
  state : null,
  win: null,
  eOut : null,
  lastE : null,
  enabled : true,
  reverse : true,
  busy : false,
    isOpening : false,

  open : function (){
    var t = WinLog;

    function eventButClear(){
      var t = WinLog;
      t.lastE = null;
      t.eOut.innerHTML ='';
    }
    function eventButReverse(){
      var t = WinLog;
      if (t.busy)
        return;
      t.busy = true;
      if (t.reverse){
        t.win.document.getElementById('wlRev').value= 'Top';
        t.reverse = false;
      } else{
        t.win.document.getElementById('wlRev').value= 'Bottom';
        t.reverse = true;
      }
      var n = t.eOut.childNodes.length;
      if (n < 2)
        return;
      for (i=n-2; i>=0; i--){
        t.eOut.appendChild (t.eOut.childNodes[i]);
      }
      t.busy = false;
    }
    
    if (!t.win || t.win.closed){
            t.isOpening = true;  
            // Firefox bug??? It appears as if a new thread is started on open, withOUT reusing same window
            //t.win = window.open('', 'uwtrace', 'top=30,left=0,width=900,height=700,scrollbars=no,location=no,menubar=no,directories=no,status=no');
            t.win = new CPopup('ptwinlog', 0, 0, 600, 800, true, function(){t.win.destroy(); t.win=null; t.win.closed=true;});
            t.win.show(true);
            t.isOpening = false; 
            t.state = null; 
    }
    
    if (t.state == null){
        
      t.win.getMainDiv().innerHTML = '<STYLE>pre{margin:0px} hr{margin:3px; height:1px; border:0px; color:#cee; background-color:#cee}</style>\
        <BODY style="margin:0px; padding:0px; border:none">\
        <DIV id=winlogtop style="background-color:#d0d0d0; margin:0px; padding:0px; border:1px solid">\
        <INPUT id=wlClear type=submit value="Clear"> &nbsp; <INPUT id=wlRev type=submit value="Bottom"></div>\
        <DIV id=wlOut style="overflow-y:auto; overflow-x:auto; max-height:800px; width:600px"></div></body>';
      t.win.getTopDiv().innerHTML = '<b class="topInfo">Info</b>';
            document.getElementById('wlClear').addEventListener('click', eventButClear, false);
      document.getElementById('wlRev').addEventListener('click', eventButReverse, false);
      t.eOut =  document.getElementById('wlOut');
      t.lastE = null;
      t.state = 1;
    }
  },

  writeText : function (msg){
    WinLog.write (msg.htmlEntities());
  },
  
  write : function (msg){
    var t = WinLog;
    if (!t.enabled || t.isOpening)
      return;
    t.open();
    var te = document.createElement('pre');
    var now = new Date();
    var m = [];
    var millis = now.getMilliseconds();
    m.push (now.toTimeString().substring (0,8));
    m.push ('.');
    if (millis<100)
      m.push('0');
    if (millis<10)
      m.push('0');
    m.push(millis);
    m.push (': ');
    m.push (msg);
    te.innerHTML = m.join('');

    if (t.reverse){
      if (t.lastE == null){
        t.eOut.appendChild(te);
        t.lastE = te;
      } else {
        t.eOut.insertBefore(te, t.lastE);
      }
      var hr = document.createElement('hr');
      t.eOut.insertBefore(hr, te);
      t.lastE = hr;
    } else {
      t.eOut.appendChild(te);
      t.eOut.appendChild(document.createElement('hr'));
    }
  },
};

